Tagged: ruby_on_rails

Elastic Cloud Computing

One of the most difficult tasks when putting up a new site is picking the right host. Moving hosts later on is terribly difficult so choosing the correct hosting company is as important as selecting a business partner. I've collected about 30 hosting companies in my delicious bookmarks. Some are specific to a platform others are really cheap. I recorded them because they looked interesting.

The latest movement in web hosting is towards cloud hosting. This is the holy grail for the user and for the hosting company. Imagine a web host that scales as you grow. Everyone would love nothing more than a host that could handle getting slammed by Digg.

Amazon's ec2 service offers scalable services, but it is not a simple as your typical web hosting company. The Ruby gem ec2onrails will simplify the process of getting your Ruby on Rails application up an running. RightScale builds on ec2 to make it easy to deploy your application. They add a dashboard and make it easy to load balance and...

Continue Reading →

rFacebook and redirect_to

I have been working with rFacebook to try to get a Facebook application up and running. Right now we are trying to integrate our conference application - 51weeks.com with Facebook so that our users can take advantage of existing social networks instead of having to create yet another network at he conference they are attending.

In working on the application I kept getting an exception related to redirect_to:

wrong number of arguments (2 for 1) 

The stack trace points to this file:

controller_extensions.rb:463:in `url_for__ALIASED'

So I did what any good developer would do I went to Google and came up with this post.

The poster replaced this line in the gem:


  path = url_for__ALIASED(options, *parameters)

with this:


  path = options

I am not brave enough to mess around with the gem - it makes deployment a bit of a headache so I sat back and thought about this for a bit. This always helps me. I checked my facebook.yml file. I have been using '/' as the callback_path. ...

Continue Reading →

Quick Note About rFacebook, Edge Rails, and Sessions.

This problem may not be specific to rFacebook, but when I added acts_as_facebook_user to my user model and then made a call like:


my_user.first_name

I would get an 500 internal server error. I checked the log and saw this: CGI::Session::CookieStore::CookieOverflow

I found that if I changed the app so that it uses db sessions everything started working.

Uncomment this line in environment.rb:


config.action_controller.session_store = :active_record_store

Make sure to add the session tables to your db by using the rake task and you should be good to go. Note that I am running edge rails so keep that in mind if you use this advice.

Continue Reading →
the generated anchor tag won't cause you problems so I don't want to hear any whining:


Delete Course

I included rails.js which will turn those links into DELETE requests for the server. However, I started seeing this error in Firebug on Firefox:


document.on is not a function

I also got this in Google Chrome:


Uncaught TypeError: Object # has no method 'on'

Turns out that since I use...

Continue Reading →

Get jQuery Working With Ruby on Rails 3

I thought I had fixed everything and made ready for Rails 3 in my applications. Turns out I was wrong. My wife tells me I'm wrong all the time so I didn't feel to bad. The first sign was that something bad had happened was that all my delete links stopped working. I found a couple of articles talking about the new unobtrusive javascript in Rails.

I have bits of code that look like this:


<%= link_to 'Delete Thing', @thing, :confirm => 'Are you sure?', :method => :delete %>

I know the argument that you shouldn't use links for delete. In this case the generated anchor tag won't cause you problems so I don't want to hear any whining:


Delete Course

I included rails.js which will turn those links into DELETE requests for the server. However, I started seeing this error in Firebug on Firefox:


document.on is not a function

I also got this in Google Chrome:


Uncaught TypeError: Object # has no method 'on'

Turns out that since I use...

Continue Reading →

Exception Handling in Ruby – a Little Surprise

I've got a rake task that includes a section where I do something like this:


begin

Do some things

rescue => ex puts "Error: #{ex}" end

I know that typically you want to be specific about the errors that you catch, but in this case I just want to move on. The things that didn't happen on this pass will get caught the next time around. It turns out that this code block won't always catch every error. It took some serious thinking to figure out why. Network time out errors are not a subclass of StandardError and thus will not be caught in the block above. Instead you have to put together a block like this:


begin

Do some things

rescue => ex puts "Error: #{ex}" rescue Timeout::Error => e puts "Timeout Error: #{e}" end

That will catch the Timeout error and allow you to deal with it appropriately.

Continue Reading →

Shoulda used RSpec

I've been updating the muck gems to work with Rails 3. The change is significant and painful but in a good way. For the most part the change consists of deleting all the code you used to hack into the Rails framework and adding subclass of '::Rails::Engine'. I'll try to put together a detailed post explaining Rails 3 engines later.

The nice thing about having a test suite in place is that you can rely on those tests to ensure the upgrade is smooth. I've always written my tests in Shoulda. I like the syntax and I love the macros. However, I'm switching everything over to RSpec. Thoughtbot has declared they won't abandon the Shoulda community, but since they've made the switch to RSpec for new projects it's pretty clear that Shoulda as a stand alone project has a limited life.

Luckily I've used RSpec in a lot of other projects and it's an easy DSL to like. The conversion from shoulda to RSpec isn't a terribly difficult one. You basically ne...

Continue Reading →

Uploadify onComplete Wouldn’t Fire Until I Swore – A Lot

I've been trying to get Uploadify to work inside my uploader gem. Things went pretty well until I combined that with the muck-contents gem and tried to do multiple file uploads from within a plugin I'd written for the TinyMCE editor. At that point things got ugly.

If you do much research on Uploadify you'll find that it's pretty common to hear someone complain that the OnComplete event does not fire. There's a number of solutions that people have come up with, but mostly they sound like voodoo - Be sure to only return a '1', make sure to use an id instead of a css class, etc. I tried everything I read about and finally got mad enough to debug the fla file.

If you are that desperate make sure to get FireFlash. It will let you write to the Firebug console from within your swf file. It's very handy when you need to see what's going on inside your Actionscript while running inside the browser. I creat...

Continue Reading →

ActiveRecord::StatementInvalid: Mysql::Error: Got error 139 from storage engine

I ran into a 'fun' error with an application I've been working on. Everything was running fine and then one day hoptoad started filling up with exceptions like this:

ActiveRecord::StatementInvalid: Mysql::Error: Got error 139 from storage engine

I hate errors like that. Lucky for me there's Google: http://forums.mysql.com/read.php?22,63584,166521#msg-166521 http://bugs.mysql.com/bug.php?id=10035

Turns out that each row in mysql has a limit of 8000 bytes. A 'text' column takes up 768 bytes in the row after that it moves the data to an db external page. When you have Rails migrations you forget how many 'text' columns you have. Turns out I had 14:

14 x 768 = 10752 bytes

What's interesting is that you can get away with this setup until one day one of your users enters a lot of data. At that moment you will get the dreaded:

ActiveRecord::StatementInvalid: Mysql::Error: Got error 139 from storage engine

Time to refactor and break the table apart. I ...

Continue Reading →

jQuery Ajax requests are ‘html’ not ‘js’

I like jQuery. I use it in all my Rails projects these days. One thing I've struggled with for the longest time is that for some reason all my jQuery ajax requests come through as html not as js.

I thought adding something like this to application.js would fix the problem:


// In application.js
jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

That won't save you. This change to Rails prevents the Accept header from being used: http://github.com/rails/rails/commit/2f4aaed7b3feb3be787a316fab3144c06bb21a27

The trick to fixing this problem comes from a comment in that commit:

Returns true if the request's "X-Requested-With" header contains

"XMLHttpRequest". (The Prototype Javascript library sends this header with

every Ajax request.)

jQuery doesn't send that parameter with each request. I've written before about modifying the request. http://www.justinball.com/2009...

Continue Reading →

Textmate RSpec Bundle Error

After installing the Textmate RSpec bundle I started getting this error:

/Applications/TextMate.app/Contents/SharedSupport/Support/lib/builder.rb:86:in blank_slate_method_added': stack level too deep (SystemStackError) from /Applications/TextMate.app/Contents/SharedSupport/Support/lib/builder.rb:86:inblank_slate_method_added' from /Library/Ruby/Gems/1.8/gems/builder-2.1.2/lib/blankslate.rb:84:in method_added' from /Library/Ruby/Gems/1.8/gems/builder-2.1.2/lib/blankslate.rb:104 from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:ingem_original_require' from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in require' from /Users/jbasdf/projects/red/vendor/rails/activesupport/lib/active_support/basic_object.rb:21 from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:ingem_original_require' from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in require' ... 32 levels... from /Users/jbasdf/Library/Application Support/TextMate/Bundles/RSpec.t...

Continue Reading →

Fireeagle and PortableContacts Don’t Get Along. That Makes Daddy Mad.

I have some code that looks like this:


  user.google.portable_contacts.all
As long as user.google is a valid token provided by oauth you will get back a list of the user's contacts from gmail.

That is unless you have the Fireeagle gem included in your application. In that case you will spend the night swearing like a sailor and then weeping openly like a little girl. If you include fireeagle 0.8.0.1 in your project and make that call you will get an error like this:


ActionView::TemplateError (wrong number of arguments (1 for 0)) on line #7 of /Library/Ruby/Gems/1.8/gems/muck-invites-0.1.12/app/views/invites/_gmail_oauth.erb:
    /Library/Ruby/Gems/1.8/gems/oauth-0.4.0/lib/oauth/consumer.rb:154:in create_http'
    /Library/Ruby/Gems/1.8/gems/oauth-0.4.0/lib/oauth/consumer.rb:154:inrequest'
    /Library/Ruby/Gems/1.8/gems/oauth-0.4.0/lib/oauth/tokens/consumer_token.rb:25:in request'
    /Library/Ruby/Gems/1.8/gems/oauth-0.4.0/lib/oauth/tokens/access_token.rb:11:inreque...

Continue Reading →

Don’t Upgrade to Rails 2.3.8 Unless You Really Mean It

I just got a new laptop which means re-installing everything. This included Rails and I ended up with 2.3.8. Most of my projects use 2.3.5. I figured no big deal since various Rails versions have always played together in the past. I installed 2.3.5 with gem install rails -v=2.3.5 and figured all would be well.

I would be wrong in that assumption.

Instead of just working anytime I try to run a 2.3.5 app (most of my apps at the moment). I get this:

Missing the Rails 2.3.5 gem. Please `gem install -v=2.3.5 rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.

So my next step was to uninstall 2.3.8. I still get the error. I uninstalled and then reinstalled Rails and things seem to be working.

Heroku has the answer: .

This is why it's usually a good idea to wait a little while after a Rails update. I have to keep reminding myself of that.

Continue Reading →

Setting Up mysql as utf8 for Ruby on Rails using homebrew

It took me far to much time to get this to work right so hopefully this is helpful for someone (probably me at some point in the future).

The hashrocket guys have a great writeup on configuring your development environment. I didn't need some of their bash configuration but it's a great starting place.

Once you have mysql installed with homebrew it can still be handy to customize your mysql configuration. Here's an article on how to configure my.cnf.

My configuration ended up looking like the code below which I got from this article. Here's more info on the values you can specify. I placed the code into '/etc/my.cnf'. That's probably more global than most people want, but it works great for me.

[mysqld]
#Max packetlength to send/receive from to server.
max_allowed_packet=64M
#socket = /var/mysql/mysql.sock
character-set-server = utf8
default-character-set = utf8

#This option makes InnoDB to store each created table into its own .ibd file.
innodb_file_per_ta...

Continue Reading →

Mountain West Ruby Conference

I spent last week at the Mountain West Ruby Conference which is by far the best conference I've ever attended due to the brilliant minds that gather from all over the country. This year Yukihiro Matsumoto (Matz), the creator of ruby came from Japan to provide his aura to to adoring minions. I had the fortune to go to dinner and hang out with him a bit which was not an insignificant opportunity. I have to admire someone who is passionate about a programming language for the sake of the language. His brainchild powers many of the latest startups and provides jobs for thousands if not hundreds of thousands of people. I asked what he thought about the significance of his contributions to the world. He said "ya, I guess it's pretty cool". For a guy that has every right to be impressed with himself he's really nice and humble. I think the ruby community not only owes thanks for a great tool, but also for a personality that helped breed a friendly, helpful bunch of peopl...

Continue Reading →

Add Theming Engine to Your Rails Application

I've written about the disguise gem before, but I've made enough changes that it warrants a new blog post. I noticed a few performance problems which have now been fixed and the configuration has been cleaned up a bit.

Disguise makes it simple to swap out the views used by your rails application either by selecting a theme using an admin UI or by changing out the theme based on the current url. For most apps the feature is probably not relevant, but if you are building a piece of software like a blog or social network then letting your users customize the look of the site is crucial to adoption.

Find the install instructions on the project's github account.

While setting a given theme works fine and doesn't incur much of a performance hit beyond method call, swapping out the theme based on the current domain can incur a performance hit since it reloads the localization strings. Here's the bit of code that swaps the views:


      def setup_theme
        return if ...

Continue Reading →

acts_as_taggable libraries and the big case problem.

Over the years I've had a chance to use the three tagging libraries available for Ruby on Rails:

I think the original acts as taggable is now defunct. The other libraries are derivatives of that library. In using tags on various sites the problem I always seem to run across is how to deal with tag case. For example, to some blue is the same as Blue. However, is god the same as God? It depends on who you ask. It seems that acts-as-taggable-on handles the case problem properly. I noticed that if I add the tag 'blue' to an object I cannot add another tag called 'Blue'. However, if I delete 'blue' and then add the tag 'Blue' it works as expected and the upper case tag becomes associated with the object.

acts_as_taggable_on_steroids doesn't handle the case problem especially well and I frequently run across this error:


  ActiveRecord::RecordInvalid (Validation fai...

Continue Reading →

undefined method `assert_no_difference’ and `assert_difference’

I've been upgrading some old code and noticed that my unit tests started spitting out a lot of errors like this:


undefined method `assert_no_difference'

and


undefined method `assert_difference'

It turns out that I needed to change my base classes from Test::Unit::TestCase to ActiveSupport::TestCase:


class UserTest < Test::Unit::TestCase

stuff

end

changes to:


class UserTest < ActiveSupport::TestCase

stuff

end

Continue Reading →

Using the OAuth and OAuth-Plugin gems

For quite a while I've been wanting to play with OAuth and now that I've been able to spend some time playing with it I have to say it is awesome. Instead of asking for a user's username and password for a given service (like their GMail or LinkedIn account) you instead have the user log into their account and grant your application access. The benefit is that your application doesn't have to figure out how to securely store a bunch of extra usernames/passwords and the user can turn off access anytime they feel like they need to reclaim their privacy.

In Rails the way to work with OAuth is the OAuth gem and the OAuth-Plugin gem which take almost all the pain out of implementing an OAuth solution. A big thanks to Pelle Braendgaard for a great library.

I won't go into all the details on how to implement the gems in your project. Instead checkout the README for each gem and the articles on Pelle's blog: Developing OAuth clients in Ruby, Major update to Ruby on ...

Continue Reading →

Ruby on Rails i18n with the Rails I18n Textmate bundle

For the longest time I've deal with internationalization in Ruby on Rails by hand. This is a tedious process that involves switching back and forth between the file containing the string and your localization yaml file. I was looking at Ruby Mine and found that it supports localization and appears to do many of the things that I like about Textmate. I've used Resharper with Visual Studio in the past and I admit that I can't live without it in the .Net world. I downloaded the Ruby Mine demo and tried it out on an existing project. For some reason the popup that is supposed to say 'I18n string value' that they show in the demos never came up for me unless I changed my strings from

<p>Some String</p>
to
<%= 'Some String' %>
I didn't really feel like having to change my string into that format was going to help my productivity so I abandoned Ruby Mine and instead started looking at the Rails I18n Textmate bundle from Sven Fuchs. Look inside the ...

Continue Reading →

Ruby on Rails i18n with the Rails I18n Textmate bundle

For the longest time I've deal with internationalization in Ruby on Rails by hand. This is a tedious process that involves switching back and forth between the file containing the string and your localization yaml file. I was looking at Ruby Mine and found that it supports localization and appears to do many of the things that I like about Textmate. I've used Resharper with Visual Studio in the past and I admit that I can't live without it in the .Net world. I downloaded the Ruby Mine demo and tried it out on an existing project. For some reason the popup that is supposed to say 'I18n string value' that they show in the demos never came up for me unless I changed my strings from

<p>Some String</p>
to
<%= 'Some String' %>
I didn't really feel like having to change my string into that format was going to help my productivity so I abandoned Ruby Mine and instead started looking at the Rails I18n Textmate bundle from Sven Fuchs. Look inside the ...

Continue Reading →

River – Amazon Wishlist Gem

One more post on Amazon Wishlist code. As another follow up to my post on Amazon Wishlist RSS, Ruby and Signing/Authenticating your Requests and the site I built to run the code My Amazon Feeds (post here) I've created a gem to contain all the code. Get it by running


  sudo gem install river

It's a pretty simple gem so working with the code is also pretty easy to do:


am = AmazonRequest.new(amazon_access_key_id, amazon_secret_access_key, ecs_to_rss_wishlist, amazon_associate_tag)
results = am.get_amazon_feeds(username) # username needs to be the user's Amazon email
feeds = results.collect { |result| OpenStruct.new(:url => result, :title => 'Amazon Wishlist', :name => 'wishlist') }

Get amazon_access_key_id and amazon_secret_access_key from your AWS console. The amazon_associate_tag parameter is optional. Throw it in there if you want your Amazon associate information in the feed. May as well :-).

The one parameter that might be confusing is &#...

Continue Reading →

Heroku

I've watched Heroku for a while. I've even tried to deploy an app there a few times, but never got into it that much. I needed a cheap (free) place to put My Amazon Feeds.com. It's just a utility site. It's not meant to scale or be production worthy. Instead it's meant to show off some code and I didn't want to spend a long time messing with deployment.

Turns out deployment on Heroku is pretty simple if you don't need a lot of custom setup. Their instructions are pretty clear so I won't repeat them. There are a few things you will want to keep in mind:

  1. You will need to create a file in the root called .gems. Mine looks like this:
    
    mislav-will_paginate --source http://gems.github.com
    httparty
    river
    
  2. Heroku uses PostgreSQL. If you have MySQL specific code or even some sloppy migrations you might have a few problems.
  3. The Heroku file system is read-only. This has some interesting side effects include the fact that your caching will ...

Continue Reading →

noconfigured for

If you are using Jeweler and get this error:

no configured for

Check out the troubleshooting section:

You need to edit ~/.rubyforge/auto-config.yml and make sure processor_ids is set like this:

processor_ids:
        IA64: 6000
        AMD-64: 1500
        Any: 8000
        Sparc: 4000
        PPC: 2000
        Other: 9999
        Alpha: 7000
        i386: 1000
        UltraSparc: 5000
        MIPS: 3000

Continue Reading →

Gems on an EngineYard Solo instance

I started running into a few issues on an Engineyard Solo instance with my muck gems. Basically, muck consists of a lot of Rails engines packaged as gems for reusability. When we release a new app we also need to release new versions of the gems since that's where most of guts of the lives. This worked fine until recently when we rebuilt our instance (to switch to Passenger). In the past a wait of about ten minutes was sufficient for the new gems to show up. The problem was that I would do a sudo gem install muck-engine and no matter how much cussing I did I ended up with the old version not the new one that I just released. I checked gem env and http://gems.rubyforge.org was listed as a source. Thanks to Ezra I found out that Engineyard maps http://gems.rubyforge.org to a local mirror. If you want to change it just edit /etc/hosts and comment out the line that looks like this:

174.129.222.219  gems.rubyforge.org

All better again.

Continue Reading →

gems:unpack for gems that don’t unpack

I couldn't figure out why my gems wouldn't unpack until I ran across this: http://metaclass.org/2009/4/13/rake-gems-unpack. My gems have rake tasks and I have to include them in the app's rakefile to make them available so Rails won't unpack them.

I did this instead:


  def muck_gems
    ['cms-lite', 'disguise', 'uploader', 'muck-solr', 'muck-raker', 'muck-engine',
    'muck-users', 'muck-activities', 'muck-comments', 'muck-profiles', 'muck-friends',
    'muck-contents', 'muck-blogs', 'muck-shares'] #'muck-invites'
  end

execute commands in a different directory

def inside(dir, &block) FileUtils.cd(dir) { block.arity == 1 ? yield(dir) : yield } end

desc "unpacks all muck gems into vendor/gems using versions installed on the local machine." task :unpack do gem_path = File.join(File.dirname(FILE), '..', '..'...

Continue Reading →

Amazon Wishlist RSS, Ruby and Signing/Authenticating your Requests

UPDATE: If you don't want to bother with the code and instead would just like to get your Amazon.com Wishlist rss you can go here.

I've been playing with the Amazon API lately. At first I just wanted to get the RSS feed to my wish list and I followed the direction in this article on the Amazon developer site. Don't bother with that article. This one on xml.com is a bit out of date, but still useful. Getting the RSS feed for your profile on most sites is a pretty simple process. On Amazon it's not. It's a total pain in the butt. Shame on them for not making this process easier. I shouldn't have to interact with a full API just to gain access to an RSS feed. Also, for any Amazon people out there would you mind keeping your documentation up to date or at least marking old articles as invalid so that I don't waste my time with stuff that doesn't work anymore?.

OK so you don't actually care about all the crap you just want the guts. I took the b...

Continue Reading →

Updating Genlighten from Rails 2.2.2 to Rails 2.3.2

I can't resist new stuff so I'm updating Genlighten to Rails 2.3.2. This release comes with some pretty sweet additions like Rack. Here's what I had to do:

  1. Set RAILS_GEM_VERSION = '2.3.2' (easy)
  2. Removed stuff like this from my code:
    
                protect_from_forgery :except => :swfupload
                session :cookie_only => false, :only => :swfupload
              
    -- 'The :digest and :secret options to protect_from_forgery are deprecated and have no effect.' and sessions are lazy loaded now.
  3. I updated shoulda to the latest version. This resulted in a number of deprecation warnings which took me a while to fix.

The release notes are worth a read.

Continue Reading →

Updating Genlighten from Rails 2.2.2 to Rails 2.3.2

I can't resist new stuff so I'm updating Genlighten to Rails 2.3.2. This release comes with some pretty sweet additions like Rack. Here's what I had to do:

  1. Set RAILS_GEM_VERSION = '2.3.2' (easy)
  2. Removed stuff like this from my code:
    
                protect_from_forgery :except => :swfupload
                session :cookie_only => false, :only => :swfupload
              
    -- 'The :digest and :secret options to protect_from_forgery are deprecated and have no effect.' and sessions are lazy loaded now.
  3. I updated shoulda to the latest version. This resulted in a number of deprecation warnings which took me a while to fix.

The release notes are worth a read.

Continue Reading →

to_json gives TypeError Exception: wrong argument type Hash (expected Data)

Tonight for no apparent reason my tests started turning up this error whenever I tried to call to_json:


TypeError Exception: wrong argument type Hash (expected Data)
Specifically, my to_json call looked like this:


respond_to do |format|
  format.js { render :json => @states.to_json(:only => [:id, :name]) }
end
In the debugger .to_json worked but to_json(:only => [:id, :name]) did not.

Needless to say given that since I hadn't touch this code in a while I was not happy and spent some time describing my code with colorful metaphors. Nothing makes me crazy like code that magically stops working.

Turns out I had installed shvets-google_translate that depended on json_pure. json_pure doesn't seem to play nice with activesupport.

For some that works. For me it did not. Apparently, Active Support and JSON gems don't play nice.

No more colorful metaphors (for now).

UPDATE Ruby on Rails 2.3.3 fixes this problem with as_json. Thanks guys!

Continue Reading →

Interesting testing issue with Rails 2.3.3

I'm not sure if this applies to all the versions of Rails, but right now I'm using the latest 2.3.3. I'm using shoulda to do testing and my code looks like this:


    context "GET show" do
      setup do
        @feed = Factory(:feed)
        get :show, :id => @feed.to_param
      end
      should_not_set_the_flash
      should_respond_with :success
      should_render_template :show
    end

The method I am testing looks like this:


  def show
    @feed = Feed.find(params[:id])
    @entries = @feed.entries
    respond_to do |format|
      format.pjs { debugger; render :template => 'feeds/show', :layout => false }
      format.json { render :json => @feed.as_json }
      format.html { render :template => 'feeds/show', :layout => params[:layout] || true  }
    end
  end

The result of running this test is: Missing template feeds/show.erb in view path app/views

That is very irritating.

I found that if I change the order as below ev...

Continue Reading →

jQuery.ajax – Get in Firefox, Post in Internet Explorer

The docs for jQuery.ajax indicate that by default the request is made using 'GET'. I would still recommend setting the type to 'GET'. We just deployed a site and found that for some reason some versions of Internet Explorer were doing a POST instead of a GET. This is problematic with a Ruby on Rails site since the same url routes to different locations based on the HTTP verbs. We couldn't figure out why we were getting a bunch of incorrect create requests until we realized the before stated issue.

I suck and I am a liar. I thought that adding GET to the ajax request fixed it but in fact it did not. I spent most of the night going WTF without any LOL while my PPH started going through the roof. The air started to stink from the foul language. No wonders I am losing all my hair.

I finally chose to gird up my loins, turn my back on the Mac, and use my PC. I fired up Visual Studio 2008 attached it to Internet Explorer and prepared a full barrage of colorful met...

Continue Reading →

jQuery.ajax – Get in Firefox, Post in Internet Explorer

The docs for jQuery.ajax indicate that by default the request is made using 'GET'. I would still recommend setting the type to 'GET'. We just deployed a site and found that for some reason some versions of Internet Explorer were doing a POST instead of a GET. This is problematic with a Ruby on Rails site since the same url routes to different locations based on the HTTP verbs. We couldn't figure out why we were getting a bunch of incorrect create requests until we realized the before stated issue.

I suck and I am a liar. I thought that adding GET to the ajax request fixed it but in fact it did not. I spent most of the night going WTF without any LOL while my PPH started going through the roof. The air started to stink from the foul language. No wonders I am losing all my hair.

I finally chose to gird up my loins, turn my back on the Mac, and use my PC. I fired up Visual Studio 2008 attached it to Internet Explorer and prepared a full barrage of colorful met...

Continue Reading →

Implicit multipart emails using Ruby on Rails and ActionMailer won’t work

I've been beating my head against the wall trying to figure out why html emails from my Rails Engine are sent out as plain text ie the email shows up with all the html tags visible. Turns out there is an issue in Rails 2.3.2:

https://rails.lighthouseapp.com/projects/8994/tickets/2263-rails-232-breaks-implicit-multipart-actionmailer-tests. For now I'm just setting my emails to html, but I'm hoping to find either a monkey patch or a Rails update that fixes the issue

Continue Reading →

Sending email with Ruby on Rails 2.3.2 and gmail

If you need an easy way to setup email for your company or for a client it's hard to not love Google Apps. (The 'standard' ie free version is here).

It is very likely that at some point you will need to send out emails from your application. Don't cry. Gmail can do this for you. Rails 2.3.2 makes it easier than ever with the addition of 'enable_starttls_auto'. Put the following code in production.rb, development.rb or environment.rb and you 'should' be able to send out emails:


  ActionMailer::Base.smtp_settings = {
    :enable_starttls_auto => true,
    :address        => 'smtp.gmail.com',
    :port           => 587,
    :domain         => 'your.domain.com',
    :authentication => :plain,
    :user_name      => '[email protected]',
    :password       => 'some_password'
  }

If you are one of the lucky ones this will actually work. It didn't work for me but since I still needed to get em...

Continue Reading →

jeweler and the empty gemspec

I've been racking my brain trying to figure out why my gemspec for a new gem had no files in it. I'm using jeweler to build the gem and it's worked great in the past. Then I read in the docs that jeweler will include any files in the gemspec that are not in .gitignore and it occurs to me that jeweler is getting the list of files from git. That means you have to do 'git init' and 'git add .' in order to have any files in your project.

So the next time you are building a gem and you do this:


    gemspec.files.include %w(
                            tasks/
                            db/migrate/.rb
                            app////
                            config/
                            locales/
                            rails/
                            test/*
                            lib//
                            public/**/ )

and you get this:


undefined method `include' for []:Array

Just know that your gemspec doesn't contai...

Continue Reading →

New Uploader Gem

I just pushed out a new uploader gem. Get the new code from github or install the gem with sudo gem install uploader. This comes with a few more translations and a fix for a nasty bug. The format was not properly set for uploads via swfupload. Unfortunately, even without the format it worked on uploads from my laptop, but not really for anyone else. I really hate that. At any rate it's fixed now.

Continue Reading →

Testing Rails Engine Gems

I've been working on a number of gems that are basically packaged Ruby on Rails engine plugins. It turns out that turning gems into plugins is pretty easy to do. However, testing them can be a pain. Here are a few things I came up with.

After looking at how Clearance handles tests I've decided that it's ok to embed a basic Rails application in your test directory.

The next trick is getting the gem you are working on to load in your embedded Rails application. The Clearance guys added a file in config/initializers that looks like this:

This simulates loading the clearance gem, but without relying on

vendor/gems

clearance_path = File.join(File.dirname(FILE), *%w(.. .. .. ..)) clearance_lib_path = File.join(clearance_path, "lib")

$LOAD_PATH.unshift(clearance_lib_path) load File.join(clearance_path, 'rails', 'init.rb')

I thought that was brilliant but it didn't work for me. After messing around in the Rails code for a bit I found a bit of he...

Continue Reading →

Testing Rails Engine Gems

I've been working on a number of gems that are basically packaged Ruby on Rails engine plugins. It turns out that turning gems into plugins is pretty easy to do. However, testing them can be a pain. Here are a few things I came up with.

After looking at how Clearance handles tests I've decided that it's ok to embed a basic Rails application in your test directory.

The next trick is getting the gem you are working on to load in your embedded Rails application. The Clearance guys added a file in config/initializers that looks like this:

This simulates loading the clearance gem, but without relying on

vendor/gems

clearance_path = File.join(File.dirname(FILE), *%w(.. .. .. ..)) clearance_lib_path = File.join(clearance_path, "lib")

$LOAD_PATH.unshift(clearance_lib_path) load File.join(clearance_path, 'rails', 'init.rb')

I thought that was brilliant but it didn't work for me. After messing around in the Rails code for a bit I found a bit of he...

Continue Reading →

A copy of ApplicationController has been removed from the module tree but is still active! And can’t dup NilClass

If you've been working on Rails 2.3 engines (the new stuff that comes with Rails 2.3 not the old engine plugin) and you start running into either of these errors:

A copy of ApplicationController has been removed from the module tree but is still active!

Or

can’t dup NilClass

Don't go find a new job at McDonald's. Read this article and feel the love again.

In fact if you do any engine or plugin or gem development read that article. It will make you happy again.

Continue Reading →

Disguise your Rails Application

I spent quite a while trying to figure out how to theme my Ruby on Rails applications. Turns out after you build a piece of software people want to use it to do other stuff. Go figure.

I really like how simple it is to skin a Wordpress site so I stole borrowed some ideas.

From all of my research and effort and late night I give you disguise the ruby gem that makes it simple to skin your Rails application and impress everyone (ok maybe your mom).

Disguise makes it possible to generate a theme for your Rails website, set the current 'theme' using an admin interface or change the theme based on the current url.

Install the gem:


  sudo gem install disguise

or get the source code at: http://github.com/jbasdf/disguise/tree/master

Continue Reading →

Disguise your Rails Application

I spent quite a while trying to figure out how to theme my Ruby on Rails applications. Turns out after you build a piece of software people want to use it to do other stuff. Go figure.

I really like how simple it is to skin a Wordpress site so I stole borrowed some ideas.

From all of my research and effort and late night I give you disguise the ruby gem that makes it simple to skin your Rails application and impress everyone (ok maybe your mom).

Disguise makes it possible to generate a theme for your Rails website, set the current 'theme' using an admin interface or change the theme based on the current url.

Install the gem:


  sudo gem install disguise

or get the source code at: http://github.com/jbasdf/disguise/tree/master

Continue Reading →

Stupid WTF! ActionView::MissingTemplate Exception: Missing template users/_user.erb

If you've spent much time working with Ruby on Rails and more especially if you've done anything with json you might have run across errors like this:


ActionView::MissingTemplate Exception: Missing template users/_user.erb

I was having this problem and doing a lot of cursing which is common when I stay up and write code until 2am which I know I should do and I also know that I shouldn't write really long run on sentences but I do it anyway.

This error is usually the result of some code that looks like this:


format.json do
  @user_html = render_to_string( :partial => 'users/user', :object => @user )
  render :json => { :success => true,
                              :user_html => @user_html  }
end

The cause of this error is that the format of the current request is :json. There isn't an _user.json.erb template so Rails tries to find an _user.erb file. That doesn't exist either and boom you spend the night sounding like a sailor.

Now I don...

Continue Reading →

Stupid WTF! ActionView::MissingTemplate Exception: Missing template users/_user.erb

If you've spent much time working with Ruby on Rails and more especially if you've done anything with json you might have run across errors like this:


ActionView::MissingTemplate Exception: Missing template users/_user.erb

I was having this problem and doing a lot of cursing which is common when I stay up and write code until 2am which I know I should do and I also know that I shouldn't write really long run on sentences but I do it anyway.

This error is usually the result of some code that looks like this:


format.json do
  @user_html = render_to_string( :partial => 'users/user', :object => @user )
  render :json => { :success => true,
                              :user_html => @user_html  }
end

The cause of this error is that the format of the current request is :json. There isn't an _user.json.erb template so Rails tries to find an _user.erb file. That doesn't exist either and boom you spend the night sounding like a sailor.

Now I don...

Continue Reading →

newgem

I've been using newgem to build Babelphish (translation helper thing). The docs from the ruby forge site are a bit out of date. If you use newgem to build anything be sure to look at this post from Dr Nic and pay attention to the options you can pass in. In particular I noticed that the instructions on the rubyforge site indicate the gem will build a default website. If you want to do that you need to pass in the -w option.

Continue Reading →

Babelphish – yml Translation Made Simple

You've just finished version one of your most excellent, million dollar application. You've built it the right way. All of your application' strings live in the en.yml file neatly tucked into the locales directory patiently waiting for the day when you hit it big, go international and hire a expensive fancy firm to translate your application for the next big market.

Why wait? Impress your friends, your family, and the ladies right now. Today. In just seconds.

With Google Translate and some gem magic your application can now impress your investors in 41 languages. Win friends and influence people in just three simple steps:

sudo gem install ya2yaml

sudo gem install babelphish

babelphish -y ./locales/en.yml -o

Viola! Your application now has a yml file for every language Google supports. -y gives the path to your source file. Feel free to start with other languages es.yml, jp.yml, etc all work just fine. -o means overwrite the files in the directory. If you have already pai...

Continue Reading →

Authorize.net – User authentication failed due to invalid authentication values

So you've worked hard to integrate your website with authorize.net and now you're ready to turn it on and make the big bucks. You run your first real transaction and get:

User authentication failed due to invalid authentication values. code="E00007"

or

This account has not been given the permission(s) required for this request.

or

E00007 User authentication failed due to invalid authentication values

You pull your hair out. You swear a lot. Then you calm down. Log into your Authorize.net account and get click on "API Login ID and Transaction Key". You probably used your login and password to access the gateway. Use the api login and key and you are good to go.

UPDATE: As Kerry pointed out you might also want to make sure you aren't pointed at the test gateway. Your production credentials won't do you any good there.

Continue Reading →

CMS Lite Gem

A pretty common problem when developing a Rails application or any web application for that matter is how to deal with content. I've often run into situations where the content development team is familiar with html and can produce reasonable content markup. Since you are going to go to all the effort and spend all the money search engine optimization (SEO) in the form of reasonable urls would be nice as well.

Enter CMS Lite.

I've just finished up a gem that makes it simple to keep the content out of the app directory and thus ensure your content developers don't have to worry about messing up code. (You can however use Ruby code in the content pages).

CMS Lite is a gem built specifically for a Rails application. You can find the code and instructions on usage here: or install the gem: sudo gem install jbasdf-cms-lite

I'm hoping to have a rubyforge project soon which will mean you will be able to install the gem this way: sudo gem install cms-lite

Just give me a few da...

Continue Reading →

CMS Lite Gem

A pretty common problem when developing a Rails application or any web application for that matter is how to deal with content. I've often run into situations where the content development team is familiar with html and can produce reasonable content markup. Since you are going to go to all the effort and spend all the money search engine optimization (SEO) in the form of reasonable urls would be nice as well.

Enter CMS Lite.

I've just finished up a gem that makes it simple to keep the content out of the app directory and thus ensure your content developers don't have to worry about messing up code. (You can however use Ruby code in the content pages).

CMS Lite is a gem built specifically for a Rails application. You can find the code and instructions on usage here: or install the gem: sudo gem install jbasdf-cms-lite

I'm hoping to have a rubyforge project soon which will mean you will be able to install the gem this way: sudo gem install cms-lite

Just give me a few da...

Continue Reading →

Rails 2.3, Nested forms and wrong constant name User[billingAttributes])

I found a chance to try out the new nested forms in a project I've been working on for a long time. (I actually tried them out a long time ago in Edge Rails, but then got burned when they pulled the functionality back out).

Everything looked like it would go well until I got this:

wrong constant name User[billingAttributes])

I cussed and cursed Rails and the plugin I am using for a few minutes and then decided that I was a grown up and a Rails programmer and I shouldn't be so stupid so I looked hard at the stack trace. It then occurred to me that I had built out a custom form builder for the project and that this error is in fact my fault.

I have some ugly code that looks like this:


  def required_field?(field)
    @object_name.to_s.camelize.constantize.reflect_on_validations_for(field).map(&:macro).include?(:validates_presence_of)
  end

Normally '@object_name' would give you the name of the object you are using like 'user' etc. However, when you are us...

Continue Reading →

Teachers Without Borders

Tonight we transferred control of the Teachers Without Borders website to a new provider. I've worked with Teachers Without Borders for more than a year now. I was granted a fellowship that allowed me to work with them to build a social network that will help teachers world-wide. Like any developer that has poured a lot of time into a project I have mixed feelings about passing the project onto another group. On the one hand it is a relief since maintenance of the project can be stressful. On the other hand not having to worry about making sure the site is running from day to day reduces a large burden.

I was talking to my wife the other day about the situations my mother-in-law, a first grade teacher, has seen over the years. In this modern age of consumerism it is easy to forget that there are many in dire circumstances. We think that the problem is out there, in Africa, in Asia, somewhere else. The truth is in this 'great nation' kids still come to school in the winter w...

Continue Reading →

Count is broken in Rails 2.3.2

After upgrading to Rails 2.3.2 I started getting this error: Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*)

It turns out that the 'count' method is broken for 'has_many through association collection with named scope'. Here's a link to the bug report:

Continue Reading →

Mountain West Ruby Conference

I've been to a good number of conferences over the years. A lot of them cost a lot of money. If you are a geek and a ruby lover (who isn't?) then the best event you'll ever attend is the Mountain West Ruby conference. The schedule is up.

It's only a hundred bucks and the best of the best show up. Get registered now so you don't hate yourself in the morning.

Continue Reading →

Mountain West Ruby Conference

I've been to a good number of conferences over the years. A lot of them cost a lot of money. If you are a geek and a ruby lover (who isn't?) then the best event you'll ever attend is the Mountain West Ruby conference. The schedule is up.

It's only a hundred bucks and the best of the best show up. Get registered now so you don't hate yourself in the morning.

Continue Reading →

Customizing the email sent by PasswordRecovery in ASP.Net

I spend most of my time working with Ruby on Rails these days. However, I still do .Net programming mainly for ThePlanCollection.com. Our password recovery system has been a bit flaky lately so I decided it was time to review the code and get it into polished condition.

I found out that I was redirecting the user to the wrong page after the password recovery and so it appeared that the password reset was failing. Big oops. While working on the code I decided that the email message were sending out sucked. Users expect more out of the web these days and we should deliver it. I found this link on customizing the password recovery control in asp.net. It is simple and to the point, but what if I want to added more customization to the message and include other dynamically generated values?

It's kind of funny how I slip into old habits when I work in the .Net world. My immediate reaction was to start searching the web for the Microsoft sanction method of passing parameters to th...

Continue Reading →

Customizing the email sent by PasswordRecovery in ASP.Net

I spend most of my time working with Ruby on Rails these days. However, I still do .Net programming mainly for ThePlanCollection.com. Our password recovery system has been a bit flaky lately so I decided it was time to review the code and get it into polished condition.

I found out that I was redirecting the user to the wrong page after the password recovery and so it appeared that the password reset was failing. Big oops. While working on the code I decided that the email message were sending out sucked. Users expect more out of the web these days and we should deliver it. I found this link on customizing the password recovery control in asp.net. It is simple and to the point, but what if I want to added more customization to the message and include other dynamically generated values?

It's kind of funny how I slip into old habits when I work in the .Net world. My immediate reaction was to start searching the web for the Microsoft sanction method of passing parameters to th...

Continue Reading →

Quick Tip for working with Paypal and ActiveMerchant in your Rails Application

Working with Paypal can be a bit difficult not because of the code required, but rather because their website can be a hassle to navigation. I already have ActiveMerchant integrated into my application. My problem was figuring out how to change it from Braintree to Paypal. Here are the quick steps for getting going.

  1. Sign up for an account here: https://developer.paypal.com
  2. Click on 'Test Accounts' then choose 'Seller' and create an account
  3. You can then use that account to login just like a real business user with the exception that you will log in to the sandbox and no money will exchange hands.
  4. If you want you can also create a 'Buyer' account that you can use to test transactions.
  5. Select the 'Seller' account and then press 'Enter Sandbox Test Site'. You will be asked to login as the 'Buyer' user. Login and then under 'My Account' which should be the first screen you see there will be 3 steps towards the bottom of t...
  6. Continue Reading →

Quick Tip for working with Paypal and ActiveMerchant in your Rails Application

Working with Paypal can be a bit difficult not because of the code required, but rather because their website can be a hassle to navigation. I already have ActiveMerchant integrated into my application. My problem was figuring out how to change it from Braintree to Paypal. Here are the quick steps for getting going.

  1. Sign up for an account here: https://developer.paypal.com
  2. Click on 'Test Accounts' then choose 'Seller' and create an account
  3. You can then use that account to login just like a real business user with the exception that you will log in to the sandbox and no money will exchange hands.
  4. If you want you can also create a 'Buyer' account that you can use to test transactions.
  5. Select the 'Seller' account and then press 'Enter Sandbox Test Site'. You will be asked to login as the 'Buyer' user. Login and then under 'My Account' which should be the first screen you see there will be 3 steps towards the bottom of t...
  6. Continue Reading →

Hierarchies, trees, jQuery, Prototype, script.aculo.us and acts_as_nested_set

'single_message' should normally be set to false. I added it in just in case I needed to render a single message for an ajax call. If you aren't rendering an entire tree and thus have only one node then passing 'single_message = true' will force the method to call the database to get the level of the node in the tree.

If you want to render a true tree structure (not just indents) then you'll need to do a bit of recursion. Assuming @message is a root level message you can do this:

    <% render_messages(@message) do |message| -%> <%= message.text %> <% end -%>


module MessagesHelper

def rendermessages(message, &block) concat('<li id="message' + message.id.tos + '" class="messageContainer delete-container">', block.binding) yield(message) concat('<ul style="display:none;" id="ul' + message.dom_id + '">', block.binding) if has_chi...

Continue Reading →

Hierarchies, trees, jQuery, Prototype, script.aculo.us and acts_as_nested_set

'single_message' should normally be set to false. I added it in just in case I needed to render a single message for an ajax call. If you aren't rendering an entire tree and thus have only one node then passing 'single_message = true' will force the method to call the database to get the level of the node in the tree.

If you want to render a true tree structure (not just indents) then you'll need to do a bit of recursion. Assuming @message is a root level message you can do this:

    <% render_messages(@message) do |message| -%> <%= message.text %> <% end -%>


module MessagesHelper

def rendermessages(message, &block) concat('<li id="message' + message.id.tos + '" class="messageContainer delete-container">', block.binding) yield(message) concat('<ul style="display:none;" id="ul' + message.dom_id + '">', block.binding) if has_chi...

Continue Reading →

Shoulda Craps out on Rails 2.2.2

I tried the latest shoulda on luvfoo a while back and it died on the internationalization stuff so we gave up. Turns out that with the new internationalization in Rails 2.2.2 shoulda is dying again. I know the code is free and shoulda really is a great project, but I think this shows why you have to be very careful about what 3rd party projects you include in your software. All of us using shoulda are now in a holding pattern until we get an update.

Continue Reading →

The binding argument of #concat is no longer needed

If you upgrade to Rails 2.2.2 and start getting "The binding argument of #concat is no longer needed" then wherever you do something like this:


concat(content, block.binding)

change it to this:


concat(content)

The 'block.binding' argument is no longer needed which is nice because who really wanted to type that over and over again anyway.

Continue Reading →

ERROR: While executing gem (ArgumentError) Illformed requirement

I like to use to deploy my applications because of its simplicity. The other nice thing is that they give you free developer space so if you are just getting an application up and running or just need to show it to a client you can do so without having to pay a bunch of money and spend a bunch of time setting up a VPS.

There are a few issues now and then. Morph has a large number of gems installed by default but occasionally I use one that they don't have. Today I ran into this problem. At first I thought no big deal I can just do a rake gems:unpack and drop the gems into the project and then deploy again.

No go.

Instead I get the following error:

ERROR: While executing gem ... (ArgumentError) Illformed requirement [""= 2.2.2""]

Turns out there is current a bug in Rails 2.1.0 and 2.2.0 that causes the unpack to barf if you specify a version number. Here's the link:

Since I am using the latest version of all the gems, my solution was to tempo...

Continue Reading →

Using Shoulda to test login – should_require_login

I've had my problems with shoulda, but one very powerful component of the testing framework is the ability to create macros. Here's one that checks to make sure a user has to be logged in to access an action. Put it into test/shoulda_macros/authentication.rb. (You can name the file anything you want I just thought authentication.rb made sense)


Test::Unit::TestCase.class_eval do
  def self.should_require_login(*actions)
    actions.each do |action|
      should "Require login for '#{action}' action" do
        get(action)
        assert_redirected_to(login_url)
      end
    end
  end
end

Then inside your controller test do something like this:


class UserControllerTest < ActionController::TestCase
  should_require_login :edit, :update, :destroy
end

Continue Reading →

Using Shoulda to test login – should_require_login

I've had my problems with shoulda, but one very powerful component of the testing framework is the ability to create macros. Here's one that checks to make sure a user has to be logged in to access an action. Put it into test/shoulda_macros/authentication.rb. (You can name the file anything you want I just thought authentication.rb made sense)


Test::Unit::TestCase.class_eval do
  def self.should_require_login(*actions)
    actions.each do |action|
      should "Require login for '#{action}' action" do
        get(action)
        assert_redirected_to(login_url)
      end
    end
  end
end

Then inside your controller test do something like this:


class UserControllerTest < ActionController::TestCase
  should_require_login :edit, :update, :destroy
end

Continue Reading →

Luvfoo – Open Source Ruby on Rails Social Network Platform

For lack of a better place to put this right now I am posting the roadmap for the Ruby on Rails social network we are building here. There has been quite a lot of interest in the project and quite a bit of willingness to contribute for which I am grateful. There are some features on this list that are a bit out there and we might not every get to. The idea is to do a brain dump and collect feedback. If you have interest or ideas feel free to add comments.

The code is currently running on: Teachers Without Borders Youth for Habitat (English, Turkish)

Get the source on GitHub

Roadmap by Feature

Featured Content

Continue Reading →

Luvfoo – Open Source Ruby on Rails Social Network Platform

For lack of a better place to put this right now I am posting the roadmap for the Ruby on Rails social network we are building here. There has been quite a lot of interest in the project and quite a bit of willingness to contribute for which I am grateful. There are some features on this list that are a bit out there and we might not every get to. The idea is to do a brain dump and collect feedback. If you have interest or ideas feel free to add comments.

The code is currently running on: Teachers Without Borders Youth for Habitat (English, Turkish)

Get the source on GitHub

Roadmap by Feature

Featured Content

Continue Reading →

Teachers Without Borders

During the day and lately most of the night I work as a Fellow for Teachers Without Borders at Utah State University. (funded by Cisco). What I actually do bores most people and causes my wife to roll her eyes and tune out anytime someone asks what I do. It's a long story and involves a lot of technical crap that few people like to hear.

For tonight I have a shorter explanation. You can see what I do. We are just polished up our latest release of the new Teachers Without Borders website.

Teachers Without Borders is a global non-governmental organization (NGO) that helps build and mentor teacher leaders around the world. The point of what we are building is to provide a place where those individuals can come together and interact and build up one another. We are still in the early stages, so expect a great deal more from the project.

The code that powers our social network is written in Ruby on Rails and is open source and MIT licensed. You can get it here:

https://github.com/jbasdf...

Continue Reading →

Teachers Without Borders

During the day and lately most of the night I work as a Fellow for Teachers Without Borders at Utah State University. (funded by Cisco). What I actually do bores most people and causes my wife to roll her eyes and tune out anytime someone asks what I do. It's a long story and involves a lot of technical crap that few people like to hear.

For tonight I have a shorter explanation. You can see what I do. We are just polished up our latest release of the new Teachers Without Borders website.

Teachers Without Borders is a global non-governmental organization (NGO) that helps build and mentor teacher leaders around the world. The point of what we are building is to provide a place where those individuals can come together and interact and build up one another. We are still in the early stages, so expect a great deal more from the project.

The code that powers our social network is written in Ruby on Rails and is open source and MIT licensed. You can get it here:

https://github.com/jbasdf...

Continue Reading →

Open Any Document in Google Docs Via a Url

We are looking at ways to integrate the new Teachers Without Borders site with Google docs.

Turns out that you can open: documents - .pdf, .doc, .txt, .html, .rtf and .odt spreadsheets - .xls, .csv, .ods presentations - .ppt

By feeding the file url to this google url:

http://docs.google.com/?DocAction=updoc&formsubmitted=true&uploadURL=DOCUMENT_URL

Here's an example if you needed to view a W4 form from the IRS url:

http://www.irs.gov/pub/irs-pdf/fw4.pdf

Use this url:

http://docs.google.com/?DocAction=updoc&formsubmitted=true&uploadURL=http://www.irs.gov/pub/irs-pdf/fw4.pdf

Continue Reading →

Using Starling, Workling with Ruby on Rails

For the project we are working on for Teachers Without Borders we need a reliable asynchronous way to process tasks. There are a myriad of ways to do this and if you aren't careful you'll spend weeks second guessing yourself while investigate every possible option. Not that I would know that from experience.

We chose Starling and Workling as our solution. Starling is a message queue that uses memcache. It was built by the guys at Twitter and released as open source. I bet it scales.

Workling is a great plugin built by a couple of guys working on boomloop.com It makes using Starling a bit easier especially when it comes to consuming messages from the queue.

There are a few blog posts around that describe how to get stuff up and running. Other than that the documentation is a bit sparse. I have to believe that will change over time. I am throwing my own links and experience into the mix so I don't forget how to do this.

First get the gems you need to run starling:


sudo gem i...

Continue Reading →

Using Starling, Workling with Ruby on Rails

For the project we are working on for Teachers Without Borders we need a reliable asynchronous way to process tasks. There are a myriad of ways to do this and if you aren't careful you'll spend weeks second guessing yourself while investigate every possible option. Not that I would know that from experience.

We chose Starling and Workling as our solution. Starling is a message queue that uses memcache. It was built by the guys at Twitter and released as open source. I bet it scales.

Workling is a great plugin built by a couple of guys working on boomloop.com It makes using Starling a bit easier especially when it comes to consuming messages from the queue.

There are a few blog posts around that describe how to get stuff up and running. Other than that the documentation is a bit sparse. I have to believe that will change over time. I am throwing my own links and experience into the mix so I don't forget how to do this.

First get the gems you need to run starling:


sudo gem i...

Continue Reading →

Tip for Testing Email with Ruby on Rails and Shoulda

Shoulda comes with a great method for testing email called 'assert_sent_email'. (If you try it and get a method missing error update Shoulda. Not that anyone wouldn't know to just do that). No matter what you use to test email as long as you are in test mode your emails will be placed into an array accessible using:


ActionMailer::Base.deliveries

This is due to this line in test.rb found in the environments folder:


config.action_mailer.delivery_method = :test

Now here's the tip. You might think you are really smart if you take advantage of the fact that Rails has a very handy initializers folder and put a file in there called mail.rb with your mail configuration.

DON'T do it. The initializer will override the value set in the test.rb file and your tests will fail.

Continue Reading →

Tip for Testing Email with Ruby on Rails and Shoulda

Shoulda comes with a great method for testing email called 'assert_sent_email'. (If you try it and get a method missing error update Shoulda. Not that anyone wouldn't know to just do that). No matter what you use to test email as long as you are in test mode your emails will be placed into an array accessible using:


ActionMailer::Base.deliveries

This is due to this line in test.rb found in the environments folder:


config.action_mailer.delivery_method = :test

Now here's the tip. You might think you are really smart if you take advantage of the fact that Rails has a very handy initializers folder and put a file in there called mail.rb with your mail configuration.

DON'T do it. The initializer will override the value set in the test.rb file and your tests will fail.

Continue Reading →

Install Native MySQL Gem – Edge Rails Stopped Including It

I decided to try out the latest edge Rails and I started getting this error:


!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
/!\ FAILSAFE /!\  Mon Jul 28 22:58:38 -0600 2008
  Status: 500 Internal Server Error
  dlopen(/Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle, 9): Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
  Referenced from: /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle
  Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle

At first I tried:


 sudo gem install mysql

which of course didn't work because it never works. You have to tell the complier where to find stuff. Do this:


sudo gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config

Continue Reading →

Install Native MySQL Gem – Edge Rails Stopped Including It

I decided to try out the latest edge Rails and I started getting this error:


!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
/!\ FAILSAFE /!\  Mon Jul 28 22:58:38 -0600 2008
  Status: 500 Internal Server Error
  dlopen(/Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle, 9): Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
  Referenced from: /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle
  Reason: image not found - /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle

At first I tried:


 sudo gem install mysql

which of course didn't work because it never works. You have to tell the complier where to find stuff. Do this:


sudo gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config

Continue Reading →

acts_as_state_machine – state is always nil

If you are using the acts_as_state_machine plugin to manage the state of your object keep this in mind: If you are going to have an object like an order or something similar that likely has a field state_id to relate in a geographic state then you need to be sure to rename the column that acts_as_state_machine plugin uses thus:


acts_as_state_machine :initial => :new, :column => :mode

Then you can get your object's state thus:


obj.mode

If you don't follow these steps ActiveRecord will override acts_as_state_machine and try to give you the geographic state (Utah, Idaho, etc) instead of the object state (new, edit, tired, etc). (In my case the value was always nil no matter how many times I tried to obj.next! to transition the states of my object. You will cry and scream and be in a very bad mood for a long time if you forget this fact.

Here's more info on the acts_as_state_machine plugin.

Continue Reading →

acts_as_state_machine – state is always nil

If you are using the acts_as_state_machine plugin to manage the state of your object keep this in mind: If you are going to have an object like an order or something similar that likely has a field state_id to relate in a geographic state then you need to be sure to rename the column that acts_as_state_machine plugin uses thus:


acts_as_state_machine :initial => :new, :column => :mode

Then you can get your object's state thus:


obj.mode

If you don't follow these steps ActiveRecord will override acts_as_state_machine and try to give you the geographic state (Utah, Idaho, etc) instead of the object state (new, edit, tired, etc). (In my case the value was always nil no matter how many times I tried to obj.next! to transition the states of my object. You will cry and scream and be in a very bad mood for a long time if you forget this fact.

Here's more info on the acts_as_state_machine plugin.

Continue Reading →

Shoulda Doesn’t like ‘Status’

One of the models in a project I am working on right now ends in 'status'. Rails handles that just find but in my tests I started noticing an odd error:


test: Lookup should belong_to lookup_status. (LookupTest):
NameError: uninitialized constant LookupStatu

The Shoulda test looks like this:


   should_belong_to :lookup_status

Nothing to complicated there. Should recognizes the relationship just find but when it tries to find a class it goes looking for LookupStatu. I fixed this by adding the the class name to the relationship thus:


belongs_to :lookup_status, :class_name => 'LookupStatus'

Continue Reading →

Shoulda Doesn’t like ‘Status’

One of the models in a project I am working on right now ends in 'status'. Rails handles that just find but in my tests I started noticing an odd error:


test: Lookup should belong_to lookup_status. (LookupTest):
NameError: uninitialized constant LookupStatu

The Shoulda test looks like this:


   should_belong_to :lookup_status

Nothing to complicated there. Should recognizes the relationship just find but when it tries to find a class it goes looking for LookupStatu. I fixed this by adding the the class name to the relationship thus:


belongs_to :lookup_status, :class_name => 'LookupStatus'

Continue Reading →

Tip for Testing Email with Ruby on Rails and Shoulda

Shoulda comes with a great method for testing email called 'assert_sent_email'. (If you try it and get a method missing error update Shoulda. Not that anyone wouldn't know to just do that). No matter what you use to test email as long as you are in test mode your emails will be placed into an array accessible using:


ActionMailer::Base.deliveries

This is due to this line in test.rb found in the environments folder:


config.action_mailer.delivery_method = :test

Now here's the tip. You might think you are really smart if you take advantage of the fact that Rails has a very handy initializers folder and put a file in there called mail.rb that contains all your email settings.

DON'T do it. That initializer will override your test settings and the email specific tests will always fail.

Continue Reading →

Tip for Testing Email with Ruby on Rails and Shoulda

Shoulda comes with a great method for testing email called 'assert_sent_email'. (If you try it and get a method missing error update Shoulda. Not that anyone wouldn't know to just do that). No matter what you use to test email as long as you are in test mode your emails will be placed into an array accessible using:


ActionMailer::Base.deliveries

This is due to this line in test.rb found in the environments folder:


config.action_mailer.delivery_method = :test

Now here's the tip. You might think you are really smart if you take advantage of the fact that Rails has a very handy initializers folder and put a file in there called mail.rb that contains all your email settings.

DON'T do it. That initializer will override your test settings and the email specific tests will always fail.

Continue Reading →

Shoulda, assert_sent_email and Unreal Users

I have been banging my head against a problem in my testing. Using the UI everything worked as expected, but my tests were failing when I tried to see if emails were being sent in a specific case.

Here's the test I was trying to run using Shoulda:


context "reset password for user that has not been activated" do
    setup do
        @email = users(:not_activated_user).email
        @emails.clear

    # this code should send out a reset password email after setting up a password reset code.
    post :create, :reset_password => {:email => users(:not_activated_user).email}
end

should "send reset notification email" do
    assert_sent_email do |email|
        email.subject =~ /You have requested to change your/ &&
        email.to.include?(@email) &&
        email.body.include?("You requested that your #{GlobalConfig.application_name} password be reset, but your account is not yet active.")
    end
end

should_set_the_flash_to(/A password reset link has...

Continue Reading →

Shoulda, assert_sent_email and Unreal Users

I have been banging my head against a problem in my testing. Using the UI everything worked as expected, but my tests were failing when I tried to see if emails were being sent in a specific case.

Here's the test I was trying to run using Shoulda:


context "reset password for user that has not been activated" do
    setup do
        @email = users(:not_activated_user).email
        @emails.clear

    # this code should send out a reset password email after setting up a password reset code.
    post :create, :reset_password => {:email => users(:not_activated_user).email}
end

should "send reset notification email" do
    assert_sent_email do |email|
        email.subject =~ /You have requested to change your/ &&
        email.to.include?(@email) &&
        email.body.include?("You requested that your #{GlobalConfig.application_name} password be reset, but your account is not yet active.")
    end
end

should_set_the_flash_to(/A password reset link has...

Continue Reading →

ActiveSalesforce and Ruby on Rails > 2.1

We have to do an integration with Saleforce for a Rails project we are working on. I keep getting this error:

The :dependent option expects either :destroy or :delete (:nullify)

I posted to the Salesforce forums and didn't get any response so I did some more investigation. Turns out there is a bug and a patch:

http://rubyforge.org/tracker/index.php?func=detail&aid=19960&group_id=1201&atid=4729

Lucky for me the latest version of Rails has a feature that unpacks all of your gems into your vendor directory. I unpacked activesalesforce, made the code changes by applying the patch (which just removes :dependent => :nullify) and viola.

Continue Reading →

ActiveSalesforce and Ruby on Rails > 2.1

We have to do an integration with Saleforce for a Rails project we are working on. I keep getting this error:

The :dependent option expects either :destroy or :delete (:nullify)

I posted to the Salesforce forums and didn't get any response so I did some more investigation. Turns out there is a bug and a patch:

http://rubyforge.org/tracker/index.php?func=detail&aid=19960&group_id=1201&atid=4729

Lucky for me the latest version of Rails has a feature that unpacks all of your gems into your vendor directory. I unpacked activesalesforce, made the code changes by applying the patch (which just removes :dependent => :nullify) and viola.

Continue Reading →

Checkbox list in Ruby on Rails using HABTM

Checkboxes are one of those things that look easy and should be easy, but they aren't always easy. I needed a solution that could create a checkbox list of languages that a user speaks. So I don't forget here's how to do it:

The migrations are important. You have to be sure to exclude the id parameter when you create languages_users or you will get ' Mysql::Error: #23000Duplicate entry' due to the fact that ActiveRecord will try to store a value in the id field that indicates which model created the entry (User.languages << vs Langauges.users). The other option is the create the id parameter so that the direction is maintained but be sure that it is not created as a primary key.


class LanguagesUsers < ActiveRecord::Migration
    def self.up
        create_table :languages_users, :id => false, :force => true do |t|
            t.integer :user_id
            t.integer :language_id
            t.timestamps
        end
    end

def self.down
    drop...

Continue Reading →

Checkbox list in Ruby on Rails using HABTM

Checkboxes are one of those things that look easy and should be easy, but they aren't always easy. I needed a solution that could create a checkbox list of languages that a user speaks. So I don't forget here's how to do it:

The migrations are important. You have to be sure to exclude the id parameter when you create languages_users or you will get ' Mysql::Error: #23000Duplicate entry' due to the fact that ActiveRecord will try to store a value in the id field that indicates which model created the entry (User.languages << vs Langauges.users). The other option is the create the id parameter so that the direction is maintained but be sure that it is not created as a primary key.


class LanguagesUsers < ActiveRecord::Migration
    def self.up
        create_table :languages_users, :id => false, :force => true do |t|
            t.integer :user_id
            t.integer :language_id
            t.timestamps
        end
    end

def self.down
    drop...

Continue Reading →

51Weeks at ICLS

Last year for our open ed conference here at Utah State I built an application called 51weeks to help preserve the presentations and to help people interact. Tomorrow it will be used at ICLS in the Netherlands. The hardest part about these kinds of applications is life cycle management. I am frequently asked to build a 'quick and dirty' application. Years of experience has taught me that there is no such thing. Anytime you are asked to build an application you are being asked to commit to keep it alive. What inevitably happens is that someone sees it and assumes that it only needs a few tweaks to adapt it to a new use. If your code is to dirty then forget it. Adaptation almost always runs you into new errors that you have to deal with in new ways.

Whenever creating an application it is always worth the time to get tests in place. It is always worth the time to think about the architecture - not the architecture for the entire system - but rather the big picture. How will the ap...

Continue Reading →

51Weeks at ICLS

Last year for our open ed conference here at Utah State I built an application called 51weeks to help preserve the presentations and to help people interact. Tomorrow it will be used at ICLS in the Netherlands. The hardest part about these kinds of applications is life cycle management. I am frequently asked to build a 'quick and dirty' application. Years of experience has taught me that there is no such thing. Anytime you are asked to build an application you are being asked to commit to keep it alive. What inevitably happens is that someone sees it and assumes that it only needs a few tweaks to adapt it to a new use. If your code is to dirty then forget it. Adaptation almost always runs you into new errors that you have to deal with in new ways.

Whenever creating an application it is always worth the time to get tests in place. It is always worth the time to think about the architecture - not the architecture for the entire system - but rather the big picture. How will the ap...

Continue Reading →

Ruby on Rails – render :action doesn’t run action

I want to be cool like everyone else so I use a REST methodology for most of my Rails controllers these days. I wasn't ever quite sure how my views managed to maintain values for a given object (User, Post, etc) after a failed call to create that that did a render :action => new. Most 'new' methods tend to do something like User.new which would create a new empty object. However, my views always had the correct values. For the longest time I have just let this go and not worried about the details, but today I started getting errors on a failed call to create in one of my controllers.

In our 'new' method we not only do User.new we also load up a bunch of data into instance variables - @states, @countries, etc. If the call to create fails we call render :action => new. This in does not invoke the 'new' method in the controller. Rather it only renders the template (which is how all your values magically stick around even on when the create fails). However...

Continue Reading →

Ruby on Rails – render :action doesn’t run action

I want to be cool like everyone else so I use a REST methodology for most of my Rails controllers these days. I wasn't ever quite sure how my views managed to maintain values for a given object (User, Post, etc) after a failed call to create that that did a render :action => new. Most 'new' methods tend to do something like User.new which would create a new empty object. However, my views always had the correct values. For the longest time I have just let this go and not worried about the details, but today I started getting errors on a failed call to create in one of my controllers.

In our 'new' method we not only do User.new we also load up a bunch of data into instance variables - @states, @countries, etc. If the call to create fails we call render :action => new. This in does not invoke the 'new' method in the controller. Rather it only renders the template (which is how all your values magically stick around even on when the create fails). However...

Continue Reading →

Ajax calls using jQuery in Ruby on Rails

jQuery is the hot javascript library and it is small and it is cooler than Prototype, the default library that comes with Ruby on Rails. Ergo I plugged it in and pulled out everything else. The ajax calls are very simple and look like this:


$.post("function_name",{ key:value } ,function(data)
{
  // do stuff with data
});

The problem is that you will start seeing 'ActionController::InvalidAuthenticityToken' and your ajax calls will fail.

Here is a very elegant solution.

Continue Reading →

Ajax calls using jQuery in Ruby on Rails

jQuery is the hot javascript library and it is small and it is cooler than Prototype, the default library that comes with Ruby on Rails. Ergo I plugged it in and pulled out everything else. The ajax calls are very simple and look like this:


$.post("function_name",{ key:value } ,function(data)
{
  // do stuff with data
});

The problem is that you will start seeing 'ActionController::InvalidAuthenticityToken' and your ajax calls will fail.

Here is a very elegant solution.

Continue Reading →

Dump an Existing Database Schema Into a Ruby On Rails Migration Ready Format

I have been looking around for a plugin or bit of code that can dump the schema from an existing database into the Ruby on Rails database migration format. The solution is a 'duh' moment, and probably obvious to most Rails programmers. All you have to do is change your database.yml file so that it points to the existing database you want to dump. Next run rake db:schema:dump. The schema.rb file in your db directory will now contain a dump of all the tables and indexes in your old database. Rename the schema.rb file to something else so that it doesn't get over written. Don't forget to change your database.yml file to back and now you only need to copy and paste what you need from the schema file into your migrations. This one should have been obvious, and it can save you an insane amount of time.

Continue Reading →

Dump an Existing Database Schema Into a Ruby On Rails Migration Ready Format

I have been looking around for a plugin or bit of code that can dump the schema from an existing database into the Ruby on Rails database migration format. The solution is a 'duh' moment, and probably obvious to most Rails programmers. All you have to do is change your database.yml file so that it points to the existing database you want to dump. Next run rake db:schema:dump. The schema.rb file in your db directory will now contain a dump of all the tables and indexes in your old database. Rename the schema.rb file to something else so that it doesn't get over written. Don't forget to change your database.yml file to back and now you only need to copy and paste what you need from the schema file into your migrations. This one should have been obvious, and it can save you an insane amount of time.

Continue Reading →

Elastic Cloud Computing

One of the most difficult tasks when putting up a new site is picking the right host. Moving hosts later on is terribly difficult so choosing the correct hosting company is as important as selecting a business partner. I've collected about 30 hosting companies in my delicious bookmarks. Some are specific to a platform others are really cheap. I recorded them because they looked interesting.

The latest movement in web hosting is towards cloud hosting. This is the holy grail for the user and for the hosting company. Imagine a web host that scales as you grow. Everyone would love nothing more than a host that could handle getting slammed by Digg.

Amazon's ec2 service offers scalable services, but it is not a simple as your typical web hosting company. The Ruby gem ec2onrails will simplify the process of getting your Ruby on Rails application up an running. RightScale builds on ec2 to make it easy to deploy your application. They add a dashboard and make it easy to load balance and...

Continue Reading →

Ruby Grand Masters

I spent two years in Japan. While there I met all kinds of interesting people. I remember one individual in particular because he was a chess grand master. He was also very good at Shogi. In fact he had written Shogi the video game for Nintendo.

I like chess and so we played a game. I thought I was a pretty good player. I used to be able to beat most casual players I met. He slaughtered me in about 10 moves. I kind of expected that. It was the most elegant butt kicking I have ever received. Grand masters think different than the rest of us. I don't remember how he beat me, but I do remember that it was smooth, quick and brutal.

This weekend I spent time with the Ruby Grand Masters. In my opinion there isn't a better Ruby conference than the Mountain West Ruby conference. The hackers show up. These guys are all about being the very best - not for money but for love of the language. Here's a list of the guys I could gather up. I am sure there were many others who didn't p...

Continue Reading →

Ruby Grand Masters

I spent two years in Japan. While there I met all kinds of interesting people. I remember one individual in particular because he was a chess grand master. He was also very good at Shogi. In fact he had written Shogi the video game for Nintendo.

I like chess and so we played a game. I thought I was a pretty good player. I used to be able to beat most casual players I met. He slaughtered me in about 10 moves. I kind of expected that. It was the most elegant butt kicking I have ever received. Grand masters think different than the rest of us. I don't remember how he beat me, but I do remember that it was smooth, quick and brutal.

This weekend I spent time with the Ruby Grand Masters. In my opinion there isn't a better Ruby conference than the Mountain West Ruby conference. The hackers show up. These guys are all about being the very best - not for money but for love of the language. Here's a list of the guys I could gather up. I am sure there were many others who didn't p...

Continue Reading →

More Ruby Conference

We missed the first talk this morning (sorry Devlin we suck). I slept till 9:30, but mainly because we were up till 4am. Dave South gave me some great info on using TestSpec. RSpec seems to be the hot thing right now, but I like how TestSpec is lightweight:

Install the gem: sudo gem install test-spec

Install the plugin: ./script/plugins install http://svn.techno-weenie.net/projects/plugins/test\_spec\_on_rails/

Require in test_helper: require 'test/spec/rails'

I spent a good part of last night rewriting some tests to use TestSpec. I also eavesdropped on a conversation the guys from EngineYard were having. They are showing their leadership in the Ruby community by sponsoring Rubinius, merb, and Datamapper, but when you listen to how knowledgeable their team you realize that they are going to play a large leadership role in the Ruby community going forward. They are awesome.

Continue Reading →

More Ruby Conference

We missed the first talk this morning (sorry Devlin we suck). I slept till 9:30, but mainly because we were up till 4am. Dave South gave me some great info on using TestSpec. RSpec seems to be the hot thing right now, but I like how TestSpec is lightweight:

Install the gem: sudo gem install test-spec

Install the plugin: ./script/plugins install http://svn.techno-weenie.net/projects/plugins/test\_spec\_on_rails/

Require in test_helper: require 'test/spec/rails'

I spent a good part of last night rewriting some tests to use TestSpec. I also eavesdropped on a conversation the guys from EngineYard were having. They are showing their leadership in the Ruby community by sponsoring Rubinius, merb, and Datamapper, but when you listen to how knowledgeable their team you realize that they are going to play a large leadership role in the Ruby community going forward. They are awesome.

Continue Reading →

Using Amazon’s Web Services from Ruby – Jonathan Younger

Right Scale has a great gem: gem install right_aws RightScale RightAws::Sqs RightScale RightAws::Ec2

They will automatically retry errors for you.

gem install kato Kato - EC2 Pool Manager


require 'rubygems'
requrie 'right_aws'
RightAws::RightAWSParser.xml_lib = 'libxml'

SQS = RightAws::Sqs.new(access_id, access_key) #get an SQS object queue = SQS.queue("name_of_queue") #create a or get a reference to an existing queue queue.psuh "put message in the queue" #8k max queue.size # get an approximate number of message in the queue message = queue.receive # message.delete # if you don't delete your messages they will show up again


require 'rubygems'
requrie 'right_aws'
RightAws::RightAWSParser.xml_lib = 'libxml'
EC2 = RightAsw::Ec2.new(access_id, access_key)
EC2.describe_instances # get a hash of running instances
EC2.run_instances("name_of_ami", minium_instances_to, max) # start up instances
EC2.terminate_in...

Continue Reading →

Using Amazon’s Web Services from Ruby – Jonathan Younger

Right Scale has a great gem: gem install right_aws RightScale RightAws::Sqs RightScale RightAws::Ec2

They will automatically retry errors for you.

gem install kato Kato - EC2 Pool Manager


require 'rubygems'
requrie 'right_aws'
RightAws::RightAWSParser.xml_lib = 'libxml'

SQS = RightAws::Sqs.new(access_id, access_key) #get an SQS object queue = SQS.queue("name_of_queue") #create a or get a reference to an existing queue queue.psuh "put message in the queue" #8k max queue.size # get an approximate number of message in the queue message = queue.receive # message.delete # if you don't delete your messages they will show up again


require 'rubygems'
requrie 'right_aws'
RightAws::RightAWSParser.xml_lib = 'libxml'
EC2 = RightAsw::Ec2.new(access_id, access_key)
EC2.describe_instances # get a hash of running instances
EC2.run_instances("name_of_ami", minium_instances_to, max) # start up instances
EC2.terminate_in...

Continue Reading →

Mountain West Ruby Conference

I'm at the Mountain West Ruby Conference for the next few days so I will be doing a bunch of blog posts that look like notes.

Up right now: Strengthening the Ruby Ecosystem & Ezra Zygmuntowicz Evan Phoenix

Evan is talking about Rubinius. Engine Yard pays him to work on the project full time. Even doesn't like the notion of a 'core' team because it implies there is one group that is above all others. The project is open source and they like to keep everyone involved. I like that. They try to be highly transparent. They are trying to build community.

Ezra is up now. I am hoping to hear something in depth about merb.

merb principles: great for mashups great for building web services grew out of frustration with Rails

Continue Reading →

Mountain West Ruby Conference

I'm at the Mountain West Ruby Conference for the next few days so I will be doing a bunch of blog posts that look like notes.

Up right now: Strengthening the Ruby Ecosystem & Ezra Zygmuntowicz Evan Phoenix

Evan is talking about Rubinius. Engine Yard pays him to work on the project full time. Even doesn't like the notion of a 'core' team because it implies there is one group that is above all others. The project is open source and they like to keep everyone involved. I like that. They try to be highly transparent. They are trying to build community.

Ezra is up now. I am hoping to hear something in depth about merb.

merb principles: great for mashups great for building web services grew out of frustration with Rails

Continue Reading →

Plugin Loading for Ruby on Rails has Changed.

I am tired of recreating the login system for Rails for each new project so using the RESTful Rails Authentication Tutorial I created a template project that I can use to create new projects. While adding in the OpenID Authentication component I started getting this error:

/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:376:in `new_constants_in': You have a nil object when you didn't expect it! (NoMethodError)

after I installed this OpenID plugin.

The problem occurs because Rails has changed the way that plugins are loaded. The default folder name was:

josh-open_id_authentication-ruby_openid_2
I renamed it to:

open_id_authentication
and everything started working again.

Continue Reading →

Plugin Loading for Ruby on Rails has Changed.

I am tired of recreating the login system for Rails for each new project so using the RESTful Rails Authentication Tutorial I created a template project that I can use to create new projects. While adding in the OpenID Authentication component I started getting this error:

/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:376:in `new_constants_in': You have a nil object when you didn't expect it! (NoMethodError)

after I installed this OpenID plugin.

The problem occurs because Rails has changed the way that plugins are loaded. The default folder name was:

josh-open_id_authentication-ruby_openid_2
I renamed it to:

open_id_authentication
and everything started working again.

Continue Reading →

Big Companies Using Ruby on Rails

I am frequently asked how reliable/scalable is Ruby on Rails? I usually tell people about Twitteror more recently point them to this article about the Friend's For Sale Facebook application. The answer is, yes Rails scales just fine. The trick is getting your database to scale.

Anyway, Obie Fernandez, a major name in the Rails community put together a list of the big companies that are using Rails.

Here are two of the places to look for the big Rails deployments: http://rails100.pbwiki.com/ http://www.workingwithrails.com/high-profile-organisations.

The elegant, framework that lets developers enjoy their job once again is scalable and will work for you application. I love Ruby on Rails.

Continue Reading →

Big Companies Using Ruby on Rails

I am frequently asked how reliable/scalable is Ruby on Rails? I usually tell people about Twitteror more recently point them to this article about the Friend's For Sale Facebook application. The answer is, yes Rails scales just fine. The trick is getting your database to scale.

Anyway, Obie Fernandez, a major name in the Rails community put together a list of the big companies that are using Rails.

Here are two of the places to look for the big Rails deployments: http://rails100.pbwiki.com/ http://www.workingwithrails.com/high-profile-organisations.

The elegant, framework that lets developers enjoy their job once again is scalable and will work for you application. I love Ruby on Rails.

Continue Reading →

Ruby fs-api

I am in the Ruby-fs API presentation now. Funding for the library came from USFamilyTree.com.

It is REST based.

Data model is: Person Person has many Assertions Assertion has one Contributor, Citation(not yet implemented), Note

Each person has a lot of data associated with them so you don't want to be parsing xml data on the fly.

Include the library with this: require 'family_tree_api/client'

The library will handle turning all the data into objects for you. This makes access to the API slick. I love ruby. ie


person = client.summary_person 'KW3B-2L7', descendants => 2
mother = person.mother
grandmother = person.mother.mother


search_params = {:givenName => 'Parker', :familyName => 'Flech'}
results = client.search search_params

As with all things Ruby this API makes it very easy to talk to FamilySearch. If you are in the genealogy space and know Ruby give it a try.

The good news is that they are open to patches. The project is in acti...

Continue Reading →

secret given to the #protect_from_forgery call

My code was running fine under Rails 2.0.2. Then I enabled the db based session store by uncommenting this:


  config.action_controller.session_store = :active_record_store
in environment.rb.

Anything that used the session after that gave me this error:


No :secret given to the #protect_from_forgery call.  Set that or use a session store capable of generating its own keys (Cookie Session Store).

If you have the same problem. Go to application.rb and uncomment the secret then restart.

All better.

Continue Reading →

secret given to the #protect_from_forgery call

My code was running fine under Rails 2.0.2. Then I enabled the db based session store by uncommenting this:


  config.action_controller.session_store = :active_record_store
in environment.rb.

Anything that used the session after that gave me this error:


No :secret given to the #protect_from_forgery call.  Set that or use a session store capable of generating its own keys (Cookie Session Store).

If you have the same problem. Go to application.rb and uncomment the secret then restart.

All better.

Continue Reading →

OER Code Sprint

We are at the end of the second day of the OER code sprint. This has been a great time feels quite a bit different than the higher level OER meetings I have attended. The first few hours of the first day were spent chatting, but after that I think that quite a bit of code has been hacked together. Normally I would oppose lots of travel decrying it as a waste of resources. However, this event has been productive. Put a bunch of smart people in a room who are capable of some kind of productive output and you will get productive output.

Here are some pictures: OER Sprint OER Sprint at COSL OER interoperability code sprint Flickr Photo Set

Continue Reading →

Professionals and The Enterprise

Professionals and the enterprise

Under threat of divorce if I didn't hang my Christmas lights this past Christmas I braved the elements and managed to put them on the trees. Of course this wasn’t sufficient to prevent the impending separation – only lights on the top eves of the house would be a sufficient sacrifice to stave off a divorce lawyer.

At great peril, a very kind neighbor and I attempted the feat. As each roof clip drew us closer to the two story eves and we had to climb higher on the roof it became clear that we would have to abort the attempt or die.

I don’t like death so we quit.

My wife didn’t really like our style of ‘safe’ decorating where the only lights were the ones we could reach so I called someone – a “professional.” I figured that a bunch of guys with safety harnesses and ladders certified by OSA would show up wearing helmets and other such gear.

Two guys showed up with a ladder, climbed up on my roof and scaled the eves learning perilously over the edge cli...

Continue Reading →

Use Mac Ports on Leopard to get Ruby on Rails Running

I am stealing this from Dave South, Logan Ruby User Group Illuminati. If I don't extract it from my email I'll never find it again. So I'll ask for Dave's forgiveness for the blatant plagiarism.

Install MacPorts, first:

http://www.macports.org

Be sure to put /opt/local/bin and /opt/local/sbin in your path.

PORT programs to install: sudo port install mysql5 server sudo port install ImageMagick sudo port install ruby sudo port install rb-rubygems sudo port install rb-termios sudo port install rb-mysql

Update GEM: sudo gem list -r sudo gem update --system

GEMs to install: sudo gem install rake sudo gem install rails sudo gem install capistrano sudo gem install mongrel sudo gem install redgreen sudo gem install test-spec sudo gem install RedCloth sudo gem install pdf-writer sudo gem install ZenTest sudo gem install mini_magick sudo gem install ruby-debug

Remember to install the mysql startup. Also, I add a mysql link in / opt/local/bin similar to the mysql5 link.

To initial...

Continue Reading →

Use Mac Ports on Leopard to get Ruby on Rails Running

I am stealing this from Dave South, Logan Ruby User Group Illuminati. If I don't extract it from my email I'll never find it again. So I'll ask for Dave's forgiveness for the blatant plagiarism.

Install MacPorts, first:

http://www.macports.org

Be sure to put /opt/local/bin and /opt/local/sbin in your path.

PORT programs to install: sudo port install mysql5 server sudo port install ImageMagick sudo port install ruby sudo port install rb-rubygems sudo port install rb-termios sudo port install rb-mysql

Update GEM: sudo gem list -r sudo gem update --system

GEMs to install: sudo gem install rake sudo gem install rails sudo gem install capistrano sudo gem install mongrel sudo gem install redgreen sudo gem install test-spec sudo gem install RedCloth sudo gem install pdf-writer sudo gem install ZenTest sudo gem install mini_magick sudo gem install ruby-debug

Remember to install the mysql startup. Also, I add a mysql link in / opt/local/bin similar to the mysql5 link.

To initial...

Continue Reading →

SWFUpload – the Best File Upload Utility for Any Platform

Uploading a file to a website is a pain. Uploading lots of files to a website makes the UN list of known methods of torture. At tonight's ruby group meeting Dave South showed off SWFUpload. This has to be one of the best uses of Flash ever. Now to upload 50 files you just browse, select them and then up they go. Dave has a great write up on using SWFUpload with Rails here. You can also find SWFUpload along with help with implementing it on other platforms here.

Continue Reading →

SWFUpload – the Best File Upload Utility for Any Platform

Uploading a file to a website is a pain. Uploading lots of files to a website makes the UN list of known methods of torture. At tonight's ruby group meeting Dave South showed off SWFUpload. This has to be one of the best uses of Flash ever. Now to upload 50 files you just browse, select them and then up they go. Dave has a great write up on using SWFUpload with Rails here. You can also find SWFUpload along with help with implementing it on other platforms here.

Continue Reading →

The Inflector Module – Another Reason to Love Rails

I love how when you need something in Rails the solution is usually already in place. For instance in the indulgenc.es application I have the need to create a rank with 1st, 2nd, 3rd etc. In most frameworks you would have to write this functionality yourself or if you are very lucky you might find something on the Internet. In Rails you do this:


number.ordinalize

Then 1 becomes 1st, 2 becomes 2nd, 1233 becomes 1233rd etc.

I am still smiling

Continue Reading →

The Inflector Module – Another Reason to Love Rails

I love how when you need something in Rails the solution is usually already in place. For instance in the indulgenc.es application I have the need to create a rank with 1st, 2nd, 3rd etc. In most frameworks you would have to write this functionality yourself or if you are very lucky you might find something on the Internet. In Rails you do this:


number.ordinalize

Then 1 becomes 1st, 2 becomes 2nd, 1233 becomes 1233rd etc.

I am still smiling

Continue Reading →

Quick Note: use rake to install Rails 2.0

I am adding this so I don't forget. You can install Rails 2.0 using this:

rake rails:freeze:edge TAG=rel_2-0-1

Then if you want to keep up the with the latest edge version you can just do the standard: rake rails:freeze:edge

Continue Reading →

Quick Note: use rake to install Rails 2.0

I am adding this so I don't forget. You can install Rails 2.0 using this:

rake rails:freeze:edge TAG=rel_2-0-1

Then if you want to keep up the with the latest edge version you can just do the standard: rake rails:freeze:edge

Continue Reading →

Configure your Free Facebook Joyent Accelerator for Capistrano

Right now Joyent is giving away free Accelerator accounts to Facebook developers. I love free stuff so this is so cool I could just cry. Free hosting with one of the premier Ruby on Rails hosts. I normally have to eat bags of M&Ms to be this happy.

Not all is roses. There is a dark side to this free hosting. Setting it up will make you want to cry. I am a developer, not a Solaris system administrator and so getting my application deployed was like having a vasectomy and being totally conscious the entire time. In hopes of saving time in the future for myself and others here is how to configure your Facebook Rails application for deployment via Capistrano on a Joyent Accelerator. The ideas aren't mine. I stole everything from all over the place. I added links at the bottom where I found some of the information. The rest of it I will just feel guilty about.

  1. Setup your shell for capistrano. Follow the link for the how and why. Note my $HOME/.ssh/environment file c...
  2. Continue Reading →

    Configure your Free Facebook Joyent Accelerator for Capistrano

    Right now Joyent is giving away free Accelerator accounts to Facebook developers. I love free stuff so this is so cool I could just cry. Free hosting with one of the premier Ruby on Rails hosts. I normally have to eat bags of M&Ms to be this happy.

    Not all is roses. There is a dark side to this free hosting. Setting it up will make you want to cry. I am a developer, not a Solaris system administrator and so getting my application deployed was like having a vasectomy and being totally conscious the entire time. In hopes of saving time in the future for myself and others here is how to configure your Facebook Rails application for deployment via Capistrano on a Joyent Accelerator. The ideas aren't mine. I stole everything from all over the place. I added links at the bottom where I found some of the information. The rest of it I will just feel guilty about.

    1. Setup your shell for capistrano. Follow the link for the how and why. Note my $HOME/.ssh/environment file c...
    2. Continue Reading →

      Setting up ZenTest and Red Green

      I can't take credit for any of these instructions. Dave South from the Logan Ruby group sent these out in an email. I am posting them so that I can find them later on.

      Install ZenTest:

      sudo gem install ZenTest

      Then install RedGreen

      sudo gem install redgreen

      Go to your rails project directory and create a file called: .autotest

      mate .autotest

      Add this to the file:

      
      require 'redgreen/autotest'
      

      Save and exit

      In your terminal, change to your rails application. Instead of typing 'rake' to run the tests, type 'autotest'. It will load the tests and run them all the first time it loads. RedGreen will highlight the result in green if everything passes and red if anything fails. Autotest will continue to run, waiting for changes in the application.

      Leave that terminal open and edit your rails application. Whenever you save the app, autotest will detect the save, identify the file(s) that changed, and run appropriate tests.

      If you change a model file, for example, a...

      Continue Reading →

      Setting up ZenTest and Red Green

      I can't take credit for any of these instructions. Dave South from the Logan Ruby group sent these out in an email. I am posting them so that I can find them later on.

      Install ZenTest:

      sudo gem install ZenTest

      Then install RedGreen

      sudo gem install redgreen

      Go to your rails project directory and create a file called: .autotest

      mate .autotest

      Add this to the file:

      
      require 'redgreen/autotest'
      

      Save and exit

      In your terminal, change to your rails application. Instead of typing 'rake' to run the tests, type 'autotest'. It will load the tests and run them all the first time it loads. RedGreen will highlight the result in green if everything passes and red if anything fails. Autotest will continue to run, waiting for changes in the application.

      Leave that terminal open and edit your rails application. Whenever you save the app, autotest will detect the save, identify the file(s) that changed, and run appropriate tests.

      If you change a model file, for example, a...

      Continue Reading →

      Stupid Error That I will Blame on Lack of Sleep

      So if you are ever working oh so hard on a ruby on rails application and all of a sudden your application stops working and you have no idea why because the error looks like this:

      
      /!\ FAILSAFE /!\  Mon Nov 12 17:27:15 -0700 2007
        Status: 500 Internal Server Error
        wrong number of arguments (1 for 0)
          /Users/jbasdf/projects/indulge/vendor/rails/actionpack/lib/
      action_controller/base.rb:513:in `send'
         .....
      

      Step back. Call yourself and idiot and remove the method you just added because you can't ever name a method 'send' in your controller because it overrides default functionality and then pukes all over the place.

      Bad programmer ... bad bad programmer.

      Continue Reading →

      Stupid Error That I will Blame on Lack of Sleep

      So if you are ever working oh so hard on a ruby on rails application and all of a sudden your application stops working and you have no idea why because the error looks like this:

      
      /!\ FAILSAFE /!\  Mon Nov 12 17:27:15 -0700 2007
        Status: 500 Internal Server Error
        wrong number of arguments (1 for 0)
          /Users/jbasdf/projects/indulge/vendor/rails/actionpack/lib/
      action_controller/base.rb:513:in `send'
         .....
      

      Step back. Call yourself and idiot and remove the method you just added because you can't ever name a method 'send' in your controller because it overrides default functionality and then pukes all over the place.

      Bad programmer ... bad bad programmer.

      Continue Reading →

      Working on Second Facebook Application

      It is top secret, but I am working on another Facebook application. This time I am using Ruby On Rails since I don't have to deal with legacy issues. I'll be interested to see if there is a large performance difference. I'll post a link when the application is ready. This time it will be for amusement and it will be funny.

      Continue Reading →

      rFacebook and redirect_to

      I have been working with rFacebook to try to get a Facebook application up and running. Right now we are trying to integrate our conference application - 51weeks.com with Facebook so that our users can take advantage of existing social networks instead of having to create yet another network at he conference they are attending.

      In working on the application I kept getting an exception related to redirect_to:

      wrong number of arguments (2 for 1) 

      The stack trace points to this file:

      controller_extensions.rb:463:in `url_for__ALIASED'

      So I did what any good developer would do I went to Google and came up with this post.

      The poster replaced this line in the gem:

      
        path = url_for__ALIASED(options, *parameters)
      

      with this:

      
        path = options
      

      I am not brave enough to mess around with the gem - it makes deployment a bit of a headache so I sat back and thought about this for a bit. This always helps me. I checked my facebook.yml file. I have been using '/' as the callback_path. ...

      Continue Reading →

      Quick Note About rFacebook, Edge Rails, and Sessions.

      This problem may not be specific to rFacebook, but when I added acts_as_facebook_user to my user model and then made a call like:

      
      my_user.first_name
      

      I would get an 500 internal server error. I checked the log and saw this: CGI::Session::CookieStore::CookieOverflow

      I found that if I changed the app so that it uses db sessions everything started working.

      Uncomment this line in environment.rb:

      
      config.action_controller.session_store = :active_record_store
      

      Make sure to add the session tables to your db by using the rake task and you should be good to go. Note that I am running edge rails so keep that in mind if you use this advice.

      Continue Reading →

      Edge Rails, OpenID and the Dreaded Sorry, the OpenID verification failed” error

      We use Edge Rails in our projects. Call me stupid if you like, I like living on the edge (get it?). This desire to push our luck has bitten us a couple of times, but not in any serious way. Not until recently anyway. We use OpenID - another brand new cool technology. The combination of Rails and OpenID has been great.

      Then one day it all stopped working and my PPH (Profanity Per Hour) went through the roof. We have Capistrano setup. I had another guy deploy 51week and OpenID stopped working and started giving me the dreaded "Sorry, the OpenID verification failed" error. I deployed it and it started working. "Very strange I thought to myself," but I was just glad it was working. Then Joel starts working on igagus. He can't login because of the dreaded "Sorry, the OpenID verification failed". We make some changes and notice that igagus no longer works.

      WTF?

      So I spend some time searching and can't find anything. I spend some time chattin...

      Continue Reading →

      Edge Rails, OpenID and the Dreaded Sorry, the OpenID verification failed” error

      We use Edge Rails in our projects. Call me stupid if you like, I like living on the edge (get it?). This desire to push our luck has bitten us a couple of times, but not in any serious way. Not until recently anyway. We use OpenID - another brand new cool technology. The combination of Rails and OpenID has been great.

      Then one day it all stopped working and my PPH (Profanity Per Hour) went through the roof. We have Capistrano setup. I had another guy deploy 51week and OpenID stopped working and started giving me the dreaded "Sorry, the OpenID verification failed" error. I deployed it and it started working. "Very strange I thought to myself," but I was just glad it was working. Then Joel starts working on igagus. He can't login because of the dreaded "Sorry, the OpenID verification failed". We make some changes and notice that igagus no longer works.

      WTF?

      So I spend some time searching and can't find anything. I spend some time chattin...

      Continue Reading →

      Ruby on Rails Tutorials

      If you love Ruby on Rails, and you should love it then you might enjoy these tutorials on Rails Forum.

      Continue Reading →

      Ruby on Rails Tutorials

      If you love Ruby on Rails, and you should love it then you might enjoy these tutorials on Rails Forum.

      Continue Reading →

      Changes to Nested Routes in Edge Rails

      When I first saw nested resources in this REST paper I thought cool that makes sense. So we started using the nested resource method in our projects. Then it got a bit wierd - like why should I have to do this/1/that/2/foo/3 if I want to get to foo. Why can't I just get to foo/3. Then I read that Jamis felt the same way.

      Well crap.

      So then I fell in love with Edge Rails and found out that the :has_many and :has_one methods have found their way into routes. (Here's the change.) This is very cool so I threw it in, but I could get the helper methods to work (stuff like entries_path(@feed) stopped working. I don't know why but I just have a heck of a time figuring out the helper methods, but they are worth using. For example future versions of Rails will replace ';' with '/' in their restful routes. If you hard coded the ';' you now have to go back and change it. You should have used the helper methods. Anyway, I found Changes to Nested Resource Routes t...

      Continue Reading →

      Changes to Nested Routes in Edge Rails

      When I first saw nested resources in this REST paper I thought cool that makes sense. So we started using the nested resource method in our projects. Then it got a bit wierd - like why should I have to do this/1/that/2/foo/3 if I want to get to foo. Why can't I just get to foo/3. Then I read that Jamis felt the same way.

      Well crap.

      So then I fell in love with Edge Rails and found out that the :has_many and :has_one methods have found their way into routes. (Here's the change.) This is very cool so I threw it in, but I could get the helper methods to work (stuff like entries_path(@feed) stopped working. I don't know why but I just have a heck of a time figuring out the helper methods, but they are worth using. For example future versions of Rails will replace ';' with '/' in their restful routes. If you hard coded the ';' you now have to go back and change it. You should have used the helper methods. Anyway, I found Changes to Nested Resource Routes t...

      Continue Reading →

      Review of Ozmozr code at Ruby Mountain West Conference

      Jamis Buck blogged about the code review of Ozmozr he and Marcel did at the Mountain West Ruby Conference. The presentation was our favorite because of the insight it gave into our code and I think we came away as better programmers for it. Here is the link to the presentation on Conference Freaks and if you want the source code they reviewed you can find it on Source Forge.

      Continue Reading →

      Presentations from Rails Conf

      In a lot of my posts I said that I would link to the presentation. All the presentations can be found here:

      http://www.web2expo.com/pub/w/51/presentations.html

      My favorites from the current list are: Building Community-focused Apps with Rails Scaling a Rails Application from the Bottom Up

      Continue Reading →

      Rails Conf after thoughts

      Now that I am home and have managed to sleep a bit I have been thinking about my overall experience at Railsconf 2007. Overall it was great. It was fun to meet so many people working in Rails. The community is filled with friendly individuals who are willing to share everything they know or just sit an chat. I even managed to get in a fun game of chess on the giant board by the vendor booths.

      My favorite talks were the ones that included code. That is probably because I am a programmer, but somehow code makes the talk real. I went to a few talks that were explanations of processes. Those are OK, but they include a lot of common sense stuff that you will already know if you have been in the field for a few years. The very best talks were ones that included code and showed best practices. I don't want to be a Rails core team fan boy, but I love to hear Jamis Buck talk. He and Koz did a great job showing off the 'Rails Way'. DHH's talk was great. He is a nice guy with grea...

      Continue Reading →

      Rails Conf after thoughts

      Now that I am home and have managed to sleep a bit I have been thinking about my overall experience at Railsconf 2007. Overall it was great. It was fun to meet so many people working in Rails. The community is filled with friendly individuals who are willing to share everything they know or just sit an chat. I even managed to get in a fun game of chess on the giant board by the vendor booths.

      My favorite talks were the ones that included code. That is probably because I am a programmer, but somehow code makes the talk real. I went to a few talks that were explanations of processes. Those are OK, but they include a lot of common sense stuff that you will already know if you have been in the field for a few years. The very best talks were ones that included code and showed best practices. I don't want to be a Rails core team fan boy, but I love to hear Jamis Buck talk. He and Koz did a great job showing off the 'Rails Way'. DHH's talk was great. He is a nice guy with grea...

      Continue Reading →

      Solr on Rails Erik Hatcher

      Ferret is fast. He has moved around and the documentation is a bit sparse. Solr was created by people at CNET, used by Internet Archive, Krugle, Revolution Health, his projects: Collext, Blacklight. Findability - serendipity is great. You should be able to browse and discover stuff you didn't intend to. Read Ambient Findability Lucene is fast and scalable. Written in Java. Solr is a layer on top of Lucene. Flare is a plugin he wrote that is a bit of a hack but does "faceted browsing, auto-suggest, folksonomy tagging/annotating." Adds caching, replication, faceting, highlighting, spell checking, Http interface. You can talk to it via Net::HTTP::Post or use solr-ruby (gem), acts_as_solr (will hopefully use gem soon, Hatcher submitted a patch)

      
        gem install solr-ruby
      

      Look at the code in his slides.

      Luke is a tool that lets you view your lucene index.

      This is a pretty sweet tool for adding search to your site. I plan on looking into it further.

      Continue Reading →

      The Rails Way Jamis Buck, Michael Koziarski

      Don't forget to look at The Rails Way blog.

      Move logic into your model. This lets you break functionality into more granular components and makes testing easier. Keep your controllers skinny. Jamis blogged about this principle here.

      Use before filters to setup state before your controller runs. Use before_create in your models.

      ActiveSupport helps you make your code intention revealing. Ruby code can be self documenting.

      has_many, belong_to makes your code powerful easy to use, but many users don’t use the power of the associations.

      
      Document.find_all_by_user_id(@john.id)

      vs

      @john.documents # this one hits the db once and then stores the objects in memory. After the call you don't have to keep hitting the db.

      You can do the same with

      
       @john.documents.find(:all, :conditions => ....
      

      try this:

      
      @cool.documents.find_by_user_id(@john.id)
      

      then define it as a method:

      
      @cool.documents_authored_by(@john.id)
      
      just be sure to not duplicate the method in both the tags and au...

      Continue Reading →

      Practical Design for Developers David Verba

      Practical Design for Developers David Verba

      Another standing room only session. Perhaps the organizers will wise up and have at least on larger room next year for the sessions that are very popular.

      We are going over the basics of audience analysis – understand your users: Context Motivations Challenges

      Know your stakeholders – anyone that has an interest in the project Understand your objectives

      Maybe it is just me but this seems like webdesign 101 it is also the standard stuff you hear in a 9th grade English class. Know your users. Talk to them. Get the goals from everyone that has a stake the project etc.

      What is interesting to me is that he seems to imply that you can figure out your ‘users’ I have been reading Don’t Make Me Think. What is interesting is that Steve Krug the author says that there are no standard users of website. There are users and they frequently use your site in unique ways that the next user will not follow. That is one thing that makes the web a unique medium....

      Continue Reading →

      Taking Care of Rails Support Tasks Through Custom Daemons Tammer Saleh

      Saleh is talking about using a Daemon to get rails to talk to LDAP. The code for the LDAP deamon and the code to make it look like a model live here. I will add a bit of code here and there, but hopefully the presenter will upload the slides so I don’t have to retype everything. There is some great code in this presentation.

      Daemons are a bit of a dark art.

      
      def daemonize
        Kernel.fork and Kernel.exit
        Process.setsid
        Kernel.fork and Kernel.exit

      system maintenance items so you don't hold up directory maintenance and so you don't have to deal with permissions

      File.umask 0 Dir.chdir '/'

      you don't want to hold onto

      ObjectSpace.each_object(IO) {|io| io.close rescue nil} STIN.open('/dev/null') end

      or just use a gem

      
      require daemons
      Daemons.daemonize

      loop {

      or whatever

      conn = accept }

      You can interact directly with your Rails environment. include environment file

      Threads ThreadsBase.allow_concurrency = true

      Or you will get a nasty error: Mysql:...

      Continue Reading →

      Bad Food

      I have eaten a lot of bad food over the past few days which is too bad given that Portland has good restaurants. The main source of bad food is the Rails conference. A WORD TO CONFERENCE ORGANIZERS: Stale pastry and coffee do not count as breakfast. Lunch is not much better. It is so bad that we went to Denny's this morning. I was forced to debug my cereal - some kind of winged ant found its way into my raisin bran. Denny's food is just nasty.

      I like Japanese food so we went looking for a Japanese restaurant last night. When we saw the place we kept walking because it looked like it would be crap. Unfortunately, all the other places were full and we were running out of time so we went back. Bad choice. If you are in Portland do not eat at Koji OsaKaya. Their food is total crap.

      I have taken to eating granola bars and bananas. Does anyone have a decent recommendation for lunch?

      PS a special thanks goes out to thoughtworks for supplying me with ALOT of granola bars.

      Continue Reading →

      Standing on the Shoulders of Giants Adam Keys

      This session is totally packed. We managed to sneak in. The door guys don't like that much. If there is a fire we will all die.

      Adam Keys is funny and entertaining

      "If you want to learn from the masters you have to read their code." Read code because "you're surrounded by idiots."

      When you read Rails code start in the routes. You can look in the url to see where you are and then go to routes to figure out where the code is.

      He is giving ideas for where to start and which parts of the app you should look at.

      My complaint about this conference is still that the sessions aren't as advanced as I would like. I would love to see a session like we had at the Mountain West Ruby conference. Jamis Buck and Marcel Molina Jr. went through some code in front of everyone (our ozmozr code actually) and pointed out everything that was wrong. It was a great learning opportunity.

      The main point of this talk is basically that you should be taking commonly used, well develo...

      Continue Reading →

      Rails Conf Intro from Chad Fowler and Some Stuff from the Mountain West Ruby Conference

      Chad Fowler is talking right now. I think he works on giving keynotes that leave you scratching your head a bit. His keynote at the Mountain West Ruby conference had mixed reviews. We left wondering what his intent was, but we weren’t sure if it was just our perception. Last night we had a chance to meet up with some of the people who were at the conference. They commented that they had a similar “huh?” moments during Fowler’s keynote. One of the guys brought his chief Java architect hoping to persuade him over to Ruby. After the talk the architects comments were, "so Ruby is slow, we shouldn't deploy on it, and you should be moving on to Haskell or Erlang anyway." I think that several people, especially the guys new to Ruby, got the impression that they were newbs polluting the Ruby world. These were the assembly programmers who weren't smart enough to jump sooner. How dare they stay in .Net, Php, or Java for so long. These guys of course are the same one who didn...

      Continue Reading →

      Rails Conf Day One Impressions

      I ended up with a major migraine yesterday towards the end of David Black’s talk so I didn’t get a chance to finish up the post. Don’t worry I probably won’t.

      My overall impression of the pre conference tutorials was that they were aimed at beginning users. If you have background in any of the topics then you might get a little value but 4 hours is a high price to pay for a little value.

      I was originally critical of the first part of Jason Hoffman’s talk but last night I met some guys that really liked it. I guess it depends on what information you need. As a side note of all the talks yesterday Jason’s is a favorite. You can download the slides from his blog. If you have to scale any kind of web application, not just Rails, download and look through his slides. There is information in there that would cost you a small fortune to research.

      We had time to chat with other developers from Utah last night. There are a decent number of guys in Utah working in either Ruby or Rails or both. W...

      Continue Reading →

      OpenID and David Heinemeier Hansson

      After the Two Revolutions session I had a few minutes to talk to DHH. First I must say he is just a very nice guy. Programmer envy over. I had a discussion about OpenID. It is going to be a critical component of the next rev of our apps. OpenID hasn’t reached a level where it has the same blessing as REST or Atom. David feels that these protocols have one and the Rails team is willing to throw their weight behind them. OpenID will likely remain a plugin for now. After spending some time with the guys developing OpenID it was interesting to get DHH’s perspective. OpenID 2.0 is coming. It has more stuff. More features etc. DHH worries that it will detract from the simplicity.

      I also had a conversation about releasing code on edge Rails. 37signals has no problem with it at all. DHH told me to freeze a version, test that and then release. This is a bit of a mind shift from the big frameworks like .net or java. If you release on a beta of either of those you will get fired and maybe sued. M...

      Continue Reading →

      Building Community-focused Apps with Rails Dan Benjamin

      Sitting in the community app presentation right now. I was torn between this and the clean code presentation, but since we are building community apps this presentation seemed to be the most appropriate.

      Here's the first slide: Fast prototyping Prototype becomes product Help Developers and Designers work together.

      I am hoping it gets better and that the intro is just a quick run through the basics. If I end up in a bunch of sessions with nothing more than common sense, basic crap I will be pissed.

      Here are my scatterbrained notes:

      Continue Reading →

      Two Revolutions Alan Francis

      I tried to get into the REST talk but it is so full that they have guys guarding the doors to keep people out. I am instead sitting in an extreme programming session. I wouldn't have come in here except I noticed that DHH walked in. I figure if he sees potential value in this talk then it is likely that I might as well.

      The talk turned out to be interesting in that it led to a discussion of revolution of of Frameworks and development philosophies. Historically, frameworks have evolved and been replaced with something new. In their wake however they leave large installations and large numbers of programmers trained in the technology. So I agree that there needs to be change and things need to get better. However, there is a need for responsibility. The success of these frameworks (like Ruby on Rails) depends on widespread adoption. Widespread adoption depends on some assurance that the framework will be around, be scalable, be developed, etc.

      Continue Reading →

      Rails Conf DHH keynote

      Listening to DHH right now. Play DHH buzzword bingo here. http://bingdoh.com/games/dhh-keynote He started out talking about the growth of the community and making fun of a job post requesting a Rails programmer with at least 3 years of Rails experience. (That is longer than he has been on Rails and he invented it.)

      Now we are going into Rails 2.0 information. DHH is talking about namespaces in routes. DHH is now building a project. Pretty cool for a keynote. DHH showed of some of the new routing features. Some example code looks like this:

      
      map.namespace(:admin) do |admin|
         admin.resources :products,
           :has_many => [ :tags, :images, :variants ]
      end
      

      Yesterday I couldn’t figure out why scaffold_resource wouldn’t work on edge rails anymore. Today I see why. The ‘generate resource_scaffold’ has been promoted to just ‘generate scaffold’. They are also getting rid of the .rhtml and .rxml formats in favor of html.erb and xml.erb.

      DHH is showing off a very cool ...

      Continue Reading →

      Rails Day One – Rails Routing

      Sitting in a session by David Black. He is talking about routing in Rails. It is starting out pretty basic, but I am hoping that it will end up covering the more complex issues as time goes on.

      We are going over named routes now. This is actually a very good tutorial, but it is aimed towards someone that has never done anything with routes.

      We are now into the second part of the session. Black is going over some of the background of rest including ideas from Roy Thomas Fielding's dissertation which is generally attributed as the beginning of REST. He said that he would focus on the more practical aspects of REST in Rails, but he can't resist talking about some theory. I am ok with that, but I have read it before. Hopefully he will get to the details of REST and routing in Rails and delve into some of the more advanced scenarios which is where we are typically having problems.

      We have started into REST in Rails. It is interesting that Black needs to caveat his comments d...

      Continue Reading →

      Rails Day One – Rails Routing

      Sitting in a session by David Black. He is talking about routing in Rails. It is starting out pretty basic, but I am hoping that it will end up covering the more complex issues as time goes on.

      We are going over named routes now. This is actually a very good tutorial, but it is aimed towards someone that has never done anything with routes.

      We are now into the second part of the session. Black is going over some of the background of rest including ideas from Roy Thomas Fielding's dissertation which is generally attributed as the beginning of REST. He said that he would focus on the more practical aspects of REST in Rails, but he can't resist talking about some theory. I am ok with that, but I have read it before. Hopefully he will get to the details of REST and routing in Rails and delve into some of the more advanced scenarios which is where we are typically having problems.

      We have started into REST in Rails. It is interesting that Black needs to caveat his comments d...

      Continue Reading →

      Rails Conference Day One

      We flew into Portland last night so that we would be ready bright and early this morning. I hate waking up at 6:30 am to go to a conference. We are programmers when will they realize that the conference should start at 11 and then run late into the night. Maybe even start at 3 and run until 1 am.

      Anyway, we went looking for a restaurant last night called Sylvias. Lucky for us they were closed permanently. We drove around looking for somewhere to eat and ended up at Wendys. So far I hate Portland. We'll see how it goes over the next few days.

      I am sitting in 'Scaling a Rails Application from the Bottom Up' by Jason Hoffman from Joyent this morning. I think I have come to the wrong session. He started by talking about how much power a server takes and how much bandwidth you may or may not need. I was hoping to see how to build a better, scalable Rails application. We aren't getting that and everything he is saying I know after running my own servers for years.

      I am thinki...

      Continue Reading →

      Rails Conference Day One

      We flew into Portland last night so that we would be ready bright and early this morning. I hate waking up at 6:30 am to go to a conference. We are programmers when will they realize that the conference should start at 11 and then run late into the night. Maybe even start at 3 and run until 1 am.

      Anyway, we went looking for a restaurant last night called Sylvias. Lucky for us they were closed permanently. We drove around looking for somewhere to eat and ended up at Wendys. So far I hate Portland. We'll see how it goes over the next few days.

      I am sitting in 'Scaling a Rails Application from the Bottom Up' by Jason Hoffman from Joyent this morning. I think I have come to the wrong session. He started by talking about how much power a server takes and how much bandwidth you may or may not need. I was hoping to see how to build a better, scalable Rails application. We aren't getting that and everything he is saying I know after running my own servers for years.

      I am thinki...

      Continue Reading →

      Something Scrumdidilyumptious

      Just short of a year ago I hacked together a project that we loving called scrumdidilyumptio.us. I and Wiley managed to finish it at about 2 in the morning in a hotel in NY during the Mellon meeting. (I actually worked on it during the meeting which resulted in terrible embarsement when my system speaker went off for a few minutes during a talk from MIT because of a misstep in setting up my database.) At any rate Wiley finally decided to say something about it which is important because people actually read his blog. He has a sweet idea that integrates with 43things. I hope to spend some time working on scrumdidilyumptious when I get back from the Identity Conference. We should be able to get a new release out in a few weeks.

      Continue Reading →

      Ruby made me fatter so I had to do something

      For years I have relied soley on typing to keep me in shape. Most of the frameworks I have used managed to help me keep the pounds off. They required plenty of code and my fingers were left in great condition. Then I found Ruby on Rails and the pounds started to come on. I just haven't been typing as much. Damn you Rails and your miniscule amount of code.

      Because of this new condition I was forced to buy a bike. Ok it might have been gas prices too. Here it is:

      http://www.jamisbikes.com/usa/bikes/06\_ventura\_elite.html

      I have almost 70 miles on it after one week which is nothing compared to all those hard core guys out there, but it helps with my new found typing exercise deficit.

      Continue Reading →

      asp.net is fun again

      I finally worked through most of the challenges I was faced with and I like asp.net again. It is interesting to program in several environments. I do a lot of Ruby on Rails these days and I love it. However, I have other applications that are written in ASP.Net. I have written quite a bit of Python code in the past few years - mainly in the context of Zope and Plone. If you were to ask me what the best web platform is I will still tell you that it depends. I think it is easy to get excited over the framework you love, or the one that you learned to program on. It is easy to become indoctrinated by the hype. However, at the end of the day I think it is best to stand back and look at the situation objectively rather than religiously. Over the years and through the platforms I have started to become more and more agnostic when it comes to my programing faith. Ruby on Rails may be new and exciting and it is fun to progam. It might even deserve all the hype it gets, but if it doesn't fi...

      Continue Reading →

      Not because I want to

      For a long time now I have been trying to figure out how to update The Plan Collection to an open source platform. I find myself updating it to ASP.Net instead. ASP.Net is ok to work with. I think Ruby on Rails is better. By better I mean simplier. ASP.Net has more stuff. It comes with all kinds of bells and whistles and millions of pages of docs to read to learn how to use it. It is more flexible than Rails and I would bet that it is faster since it is compiled, sort of.

      I do it not because I want to but because I have to. I think many software projects are that way. Building a brand new application is a luxury. You can do all kinds of things that you want to do. Maintaining an application is different. You do things because you have to. For example, The Plan Collection has about 90,000 pages in the Google index. We can't afford to throw that away so we need urls to stay the same. At least we need to be able to setup redirect so that they site still works with those urls. In addit...

      Continue Reading →

      The Plan Collection

      I have spent the past few weeks working on two projects. One is brand new and very exciting - houseplans.info. I developed that site in Ruby on Rails and it uses mysql on the backend. That project took me about four weeks working a few hours in the evenings. It is a joy to work on. I compare that to The Plan Collection which I have spent the last 7 years working on. It is written in old ASP and is painful to work on. I have been updating it to ASP.Net here and there and it just isn't as much fun as working in Ruby on Rails. By fun I mean that in twenty seconds I can setup url rewrites in Rails while I spent several days testing, debugging and cussing url rewrites in ASP.Net. I'm still not done. So far I am still unable to find a way for a form to post back to the rewritten url. ASP.Net happily ignores the rewrite and sets the form postback for you and refuses to give you a way to change it.

      Open source is so much better and lets me be in a happy place.

      Continue Reading →

      I hate RadRails

      As per my last post I am loving Ruby on Rails. The biggest drawback to the framwork is my quest to find the right editor. I have actually been using Dreamweaver when I write code on Windows. It makes me feel like a lesser programmer for some reason, but it works great. There is a plugin called RubyWeaver that makes it easy. Add into that the Subversion utility for Dreamweaver that lets you [cloak/uncloak SCM Directories][2] and you have a decent editor. (Without that last extension Dreamweaver will try to upload all the hidden Subversion directories and make a mess of you server).

      [2]: http://www.macromedia.com/cfusion/exchange/index.cfm#view=sn106&viewName=Exchange Search Details&loc=en_us&authorid=0&page=0&scrollPos=0&subcatid=0&snid=sn106&itemnumber=-1&extid=1018603&catid=0

      On Linux I have been using RadRails. It is ok most of the time. However, every now and then it drives me nuts. Today is such a day. When I copy and paste I get randon '...

      Continue Reading →

      Joining the Rails bandwagon

      I have worked in numerous roles as a programmer. My lot has been everything from low level USB firmware to Visual Test to ASP and then ASP.Net. Years ago, when I first saw ASP.Net I thought that I had found the best web framework in the world. I am working on a PhD (here and there). Last semester I worked on an independent study project (scrumdidilyumptiou.us). Most of the project was done over the course of a few weeks with the bulk of the work done during a meeting at the Melon Foundation. I am a programmer you can't expect me to listen to business like presentations can you?

      Because everyone else was doing it I decided I would give Ruby on Rails a shot. The hype isn't hype. It's the real thing. Two weeks ago in my spare time I started a project at www.houseplans.info. Its up and running now. Two weeks. I measure my Ruby on Rails projects in weeks not months. It is an amazing framework. Tonight I find myself writing ASP.Net code. I wish I wasn't. It is power. It can d...

      Continue Reading →