Rails ActiveRecord Tips

by adam on December 24, 2008

Ruby on Rails
Image via Wikipedia

After using ActiveRecord for a while, some questions keep coming up when performing operations that are more complicated than the standard create, read, update, delete.

1. Does ActiveRecord track if an attribute is has been modified? Does it track dirty state on an object or attribute basis?

Yes, but not for attributes so far as I can tell. Rails provides these great helper methods (examples given for a person sample object).

person.new_record?
person.changed?
person.name_changed?
person.name_was

person.name = 'bob'
person.changed        # => ['name']
person.changes        # => { 'name' => ['Bill', 'bob'] }

Documentation on Rails ActiveRecord dirty state methods

note that changed? does not capture if a collection has changed (nor seem to work for a collection)

2. Does ActiveRecord automatically set the reference pointers on both sides of a has_many relationship?

Surprisingly, no. For example

p = Person.new
e = EmailAddress.new
e.person = p
p. email_addresses # => []

even though EmailAddress belongs_to :person

the reverse is also true

e2 = EmailAddress.new
p.email_addresses.push(e2)
e2.entity # => nil

Also, this is the case even if p and e have been previously saved to the database.

3. Are objects automatically persisted when you insert into a collection?

Yes. From the documentation: “Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object (the owner of the collection) is not yet stored in the database.”

You can add an object to a collection without automatically saving it by using the my_collection.build method

4. How does it handle database sessions, is there support for transactions?

I don’t see any support for sessions (in the “Hibernate” sense, where you can make a number of object changes, then dump those to the database all at once). However, simple transactions are definitely supported.

ActiveRecord::Base.transaction do
  david.withdrawal(100)
  mary.deposit(100)
end

{ 2 comments }

Mac Software Recommendations

by adam on November 28, 2008

I’m making one final pass at cleaning off my hard drive this morning before installing OS X Leopard. As part of the process, I’m making sure I have license keys for all the software I’ve purchased over the last year or so. Here is a list of the software I have purchased that I recommend.

Parallels – Lets you run XP or Vista on your Mac. I am having a heck of a time getting my vista image off my hard disk, because it is 30GB, but Parallels has been great.

TextMate – I haven’t been happy with the selection of Software Development Environments’s for OpenSource software, but TextMate is light weight and gets the job done. Others I also use in are NetBeans and Aptana.

iWork – I Tried OpenOffice, but upgraded to iWork for Keynote. OpenOffice was too slow.

Flex Builder 3 – You can do Flex development without buying Adobe’s SDE, but when learning something new, every advantage helps. I found the this Eclipse derivative to be stable, and worth the price for the visual layouts and built in documentation.

Market Samurai – A great SEO keyword research tool that helps you plow through tons of keywords. It also tries to optimize the process of getting backlinks, but that is a tough problem to solve. I haven’t found Market Samurai’s ability to search for content and back links opportunities to be all that useful, but I haven’t really tried that hard.

Pixelmator – Excellent affordable Photoshop replacement. I like the support of gradients. Little bit of a learning curve (probably the same as Photoshop).

I will likely soon buy:

MacSpeech Dictate – Tried a demo of this and the speech recognition was “good enough.”

ScreenFlow – for making screen capture videos with web cam picture-in-picture.

{ 9 comments }

What is Twitter?

by adam on November 22, 2008

I’m proud of having introduced Twitter to a prominent Seattle investor a couple years back (he hadn’t heard of it – and wasn’t looking to invest in it). If you still aren’t on the bandwagon, here is a cool video explaining it. Today, I met the creator of this video. He has built a business out of handcrafted educational videos. Great stuff!

{ 27 comments }

The world needs a comprehensive internet connected set-top box. There is no existing solution that allows you to:

  • Watch Hulu, YouTube, and other streaming internet videos on your TV
  • Record broadcast TV in a portable format (an HD DVR).
  • Download (via Bit torrent or Usenet) and view downloaded videos in portable formats (DivX, Xvid, other MPEG-4 variants)

After a couple days research, it looks like the best way to accomplish this is by using a Mac or PC with a TV tuner as a home video server. In my case, I already have a MediaCenter PC, but it isn’t in the TV room, so I’ve researched the best option for sharing videos over my home network. The result is the system diagrammed below. I haven’t actually set up the UPnP part of the network yet, but I will likely use iPodifier and PlayOn to transmit shows to a PS3 (which, though expensive, is also a blue-ray player). I am willing to hack a little bit, but am hesitant to embark on a major hacking expedition (doing stuff over SSH to an AppleTV, or installing MythTV to see if it supports my video card both sound like too much work).

I prefer to pay for high speed internet rather than cable/satellite TV. For some reason, I can’t stomach a monthly subscription for TV. $50-100/month = $600-1200/yr (although I do have ultra-basic cable because our TV reception is poor). A basic HD TiVo, the leading choice for a stand-alone DVR, is $299 without programming, $700 with lifetime service. This is too expensive, and still only solves 1 of the 3 criteria above.

On demand download services are more palatable, the leaders are:

But with all of these, you pay for a limited selection of old TV shows and movies. Rather than dropping $600 on a year of cable television, that money will go a long way towards a Mac Mini with EyeTV or a MediaCenter PC. Once you have either of those as a hub, it is easier to free up your content for viewing on other devices around the house.

Here is what I’ve found to be the leading software you can install on your Mac/PC DVR to share video around the house:

  • PlayOn (UPnP server for PC)  – launched a beta version recently and their site went down
  • iPodifier (file converter for PC) to automatically convert your Windows MediaCenter format files to iPod or AppleTV friendly format (MPG-4)
  • MediaTomb (UPnP server for Mac/Linux)

These are very promising because they don’t require a lot of hacking (although MediaTomb doesn’t seem have any installation instructions)

UPnP Clients

  • PlayStation3 – should work with PlayOn and has a blue-ray drive.
  • XBox 360 – should work with PlayOn or PC MediaCenter (though I had bad experiences with first gen Xbox)
  • not AppleTV (requires hacking) – but should detect MPG-4 videos encoded by iPodifier

Other Links

{ 8 comments }

StumbleRead Feature Ideas

by adam on August 5, 2008

The generic globe logo used when Firefox is co...Image via Wikipedia

I’ve been trying to prioritize the requests I’ve had for StumbleRead. Thanks to everybody who has provided feedback.

1. Support for “Hide” (as defined by FriendFeed)

2. There is a bug when opening articles (for example from the New York Times) where the article takes over the StumbleRead frame. I’m not 100% sure I can fix this, but I will try.

3. “Next >>” bookmarklet. Just discovered that Google Reader has one of these, and it would be perfect for StumbleRead. Clicking the button would take you to the next unread item in your FriendFeed queue. (This would likely also entail “read item” tracking, though you could imagine it opening just the item with the newest comment or like).

4. Reverse sort order comments. Probably will make this a preference option.

5. Pop-out mode, where StumbleRead left hand frame becomes its own window (like a Web based Twhirl). it would still auto open posts, but allow us to see the URL of the content pane.

6. “Horizontal” mode. Just something I want to try. One item at a time in horizontal pane at the top.

7. FireFox add-in. This would probably be too much work for me to undertake. I’m hoping the combination of the above features will make an add-in unnecessary.

8. Skins. Would be great to have some alternate color schemes.

9. Search and filter. I really want to be able to filter to just videos or photos.

James Mowery has posted separately with some great suggestions for the ultimate FriendFeed client.

“Perhaps third-party developers should attempt to integrate more tabs and/or filters within a FriendFeed client. Why not have tabs or filters for each of the following: blogging activity, news activity, social networking activity, multimedia activity, shopping activity, comment activity, and more.”

#9 should cover that

“The interface should allow users to properly and intuitively manage, display, and sort comments.”

#4 should help

“Finally, the person or people who decide to make the ultimate FriendFeed client should find ways to extend FriendFeed’s uses. Honestly now, who knew that Twitter was going to be a popular service to track packages and calculate MPG rates? Who knew that it would turn the everyday person into a reporter? Who knew that it would be one of the most dominant marketing tools today? Who knew that it would change the world? FriendFeed’s third-party developers should apply all this knowledge to their creations.”

This is a big but fascinating challenge. FriendFeed is already so interoperable. What StumbleRead could do is package all the audio or video links into a playlist. Just one idea.

Zemanta Pixie

{ 0 comments }

I wrote previously about my trip to Machu Picchu when I visited Peru in May. Breathtaking as it was, it wasn’t the highlight of the trip. The highlight was seeing the work of the team at Kausay Wasi Clinic in Qoya. My father in-law has seen hundreds of patients with the team there over the last several years. The clinic provides basic health and dental care to thousands of Peru’s people who live in the rural Sacred Valley area.

“The Clinic treats approximately 10,000 patients per year, and US visiting medical teams perform approximately 300 operations free of charge in specialties such as ears, nose and throat, facial reconstruction, cataract, orthopedic surgeries for children, and gynecological surgeries for women.”

To visit was a life changing experience. The patients that we saw come through the clinic were overwhelmed with gratitude for the care they received. Care they would not have gotten if not for the efforts of the two sincere and effective founders Guido and Sandy Del Prado.

If you are traveling to Machu Picchu, or just want to make a difference, please sponsor a family. $200 will cover an entire family’s medical care for one year.

{ 0 comments }

What next for Lookmarks?

by adam on August 2, 2008

Spam musubi made from SPAM. (see definition fo...Image via Wikipedia

Lookmarks is my simple link sharing site that died under the weight of link spammers (both bots and humans). I’ve been trying to think of a way to re-work the site to capture the enthusiasm of all those unexpected “customers”. I’ve got the site half-way ported to Google App Engine, and I’m taking an internet marketing course (I’m ashamed to admit) that I’m sure will influence my ideas further.

Goal

The goal is to build a quality link directory by encouraging self promotion and harnessing it to enforce quality (like Mahalo or Wikia but with controls instead of paid editors). The business model is AdWords and paid sponsored links.

Idea

Create a “digg” like system where you only ever vote on random links. You gain or lose credibility points based on how many people later vote the same as you.

Detail

The new Lookmarks works like a very simple social bookmarking site (with a search function), except by default links you add are only visible to yourself (and your friends).

In order to make a link appear public (and to other users that are not your friends) without having other people bookmark it, you must spend Lookmarks points (or dollars). You presumably only want to do this when you are trying to promote your own site. Once public, the link appears in anonymous search results and is indexed by Google (what the link spammers want).

Points are awarded to users based on their ability to predict how many other people will bookmark or “vote up” links. The site doesn’t allow you to go around voting on links because this would allow collusion between fake user accounts. One user could follow around another, bookmark everything and earn a ton of points. You can however, visit a special voting page that presents random links that you can vote on. You are presented with a screen like:

When searching for “Seattle restaurants” do you think most people would find the link below useful, informative, or entertaining… Yes or No

The prediction scoring in this case grants you one point for all the people after you that vote the same as you, and subtracts a point for everybody who votes differently. The volume of random links prevents collusion (the database is already seeded with 10s of thousands of questionable links). Even if you teamed up to vote yes on everything with the letter “X” in it, you’d have to wade through too many links to make the points add up.

Once you’d acquired some points, you could spend/deposit them on one of your links to keep it public even if it received negative votes. For example, you could put 10 points on it to counter-act 10 negative votes.

Just to re-iterate, only link spammers and super-contributors would care about earning points. Normal users could ignore them.

Issues, Questions, Refinements

  1. Sites like delicious, faves don’t appear to need a points system – so captchas and spam filters are presumably enough to throw away the spam (discouraging the spammers instead of harnessing them).
  2. Is the visibility of points (or spending points) necessary? We could just weight the votes of people who make best predictions. The points should probably be visible though as motivation.
  3. Could streamlining the voting so that when you are submitting your link, you have to vote right then and there if you want to make your link public. Include paypal pay now button.
  4. Scoring would be slow to get going. Could give everyone 5 points to start. Could make “random” selection weighted towards links that had 1 vote to speed up scoring.
  5. How would you combine the UI of Digg and Delicious? Since use cases are different, should probably keep them separate. Could be separate views on the same database.
  6. Would it be more efficient to force comparison between two links instead of voting on one?
  7. Can I add one more feature that makes the world a better place (like improve link sharing for teams) to make this whole venture worthwhile.
  8. Other random idea: award one point for each external domain that links to lookmarks (ick :) !)

What do you think of the points system? Should it be visible or invisible? The question is not whether or not you’d use the site, but whether link spammers would bother to go through the voting exercise.

{ 1 comment }

Common Ruby Regex Patterns

by adam on July 27, 2008

My earlier (rather lame) post on Ruby Regex’s (Regular Expressions) is getting some Google love, so I thought I would supplement it with some more useful information.

If you are searching for Ruby Regex help, my guess is you are looking for…

Validating an email address with a Ruby Regex

Something simple like this next one will get you started.

irb(main):023:0> “me@adamloving.com”.match /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i

For a much more complete email address ruby regex, try:

#
# RFC822 Email Address Regex
# --------------------------
#
# Originally written by Cal Henderson
# c.f. http://iamcal.com/publish/articles/php/parsing_email/
#
# Translated to Ruby by Tim Fletcher, with changes suggested by Dan Kubb.
#
# Licensed under a Creative Commons Attribution-ShareAlike 2.5 License
# http://creativecommons.org/licenses/by-sa/2.5/
#
module RFC822
  EmailAddress = begin
    qtext = '[^\x0d\x22\x5c\x80-\xff]'
    dtext = '[^\x0d\x5b-\x5d\x80-\xff]'
    atom = '[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-' +
      '\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+'
    quoted_pair = '\x5c[\x00-\x7f]'
    domain_literal = "\x5b(?:#{dtext}|#{quoted_pair})*\x5d"
    quoted_string = "\x22(?:#{qtext}|#{quoted_pair})*\x22"
    domain_ref = atom
    sub_domain = "(?:#{domain_ref}|#{domain_literal})"
    word = "(?:#{atom}|#{quoted_string})"
    domain = "#{sub_domain}(?:\x2e#{sub_domain})*"
    local_part = "#{word}(?:\x2e#{word})*"
    addr_spec = "#{local_part}\x40#{domain}"
    pattern = /A#{addr_spec}z/
  end
end

Find URLs using a Regular Expression in Ruby

Here is a simple URL matching regular expression.

irb(main):028:0> "http://www.adamloving.com/".match /^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/.*)?$/ix

{ 1 comment }

This is a follow up post to my earlier post about watching internet video (Hulu and YouTube) on a TV. Since I still haven’t found a set top box that I can recommend, I thought it would be helpful to describe how to hook your PC or laptop up to your television.

  • If you have an older PC or laptop, and an older TV, most likely what you need is an S-video cable.
  • If you have a newer PC or laptop and an older TV, DVI to S-video is more likely what you need.
  • Lastly, if you have a new PC or laptop, and a new TV (like a flat screen LCD TV) – you probably need a DVI to HDMI cable.

Hooking up your PC to your TV can be a pain. Here is another article I found about internet set top boxes. One that looks promising that I didn’t mention before is the “vunow“. The vunow claims to offer NBC content, but I couldn’t figure out where to actually buy it – so it may not be released yet.

It seems like someone just needs to get this hardware done so we can make cable and broadcast TV obsolete.

{ 8 comments }

Hotel LarabeachImage by Abdallah ♫ via Flickr

I don’t understand how Facebook’s new Friend Connect is substantively different from their pre-platform API functionality. External Web sites already have the ability to allow users to sign in to Facebook and retrieve their friends and profile from an external site. Friend connect just appears to be some better UI controls for doing this withouth having to jump off to Facebook and approve the 3rd party app. What am I missing?

{ 1 comment }