Using Yahoo!’s BBAuth with Rails

I’ve been meaning to try simply_restul for a while now, and today’s announcement on rails-core pushed me over the edge. It’s no longer a plugin, it lost it’s name and changed a few things, but it’s pretty much the same. I’m going to do a quick tutorial on setting up a RESTful controller. It’s not hard — I was just scared of it!

rails simple

This creates a new rails project named “simple”. Without a -d flag, it will use mysql by default

cd rails

mysqladmin -u root create simple_development

mysqladmin -u root create simple_test

create our databases – if this were a longer tutorial, we’d test it as we went.

rake rails:freeze:edge

Make your project use the latest version of rails “Edge”. You have to do this if you want to follow along. In the future, this step will be unnecessary

script/generate model Person

Our example object – a Person
[source:ruby]
db/migrate/001_create_people.rb:
class CreatePeople < ActiveRecord::Migration
def self.up
create_table :people do |t|
t.column "name", :string
t.column "bio", :text
end
end

def self.down
drop_table :people
end
end
[/source]

rake db:migrate

We’re creating our table now using a migration. If everything went well, you’ll now have a table in your database – “people”, with two columns, name and bio.

Add the following line to your config/routes.rb

map.resources :people

(this is a change from simply_restful, plural now) Here is where the magic happens. This one line of code will give you a bunch of stuff. All the mappings between REST and your controller will now just work.

script/generate controller people index new create show edit update destroy

Create our controller with all the REST / rails actions.

app/controllers/people_controller.rb:

Here’s a lot of code. This is the person controller and all the actions that you want to do on a person. They map to HTTP verbs very nicely. You should type the code (the generator made a lot if it for you, you just need to fill in the methods)

You’ll notice the funny “respond_to do |format|” stuff. This is one of the other slick features: you can send the client the format they want. So if someone were to request /person/1.xml – they clearly want xml output – this handles that (and so much more).

That was all fine and good. We could write a very nice test suite for all the code to now and still be lost on the views. Let’s go through them quickly.

app/views/people/index.rhtml

app/views/people/new.rhtml

app/views/people/show.rhtml

app/views/people/edit.rhtml

app/views/people/_form.rhtml

This concludes the whirlwind tour of the new RESTful Rails controllers.
I’ll be changing this post a lot based on feedback, so check back.

REST and Rails – no reason to be scared

I’ve been meaning to try simply_restul for a while now, and today’s announcement on rails-core pushed me over the edge. It’s no longer a plugin, it lost it’s name and changed a few things, but it’s pretty much the same. I’m going to do a quick tutorial on setting up a RESTful controller. It’s not hard — I was just scared of it!

rails simple

This creates a new rails project named “simple”. Without a -d flag, it will use mysql by default

cd rails

mysqladmin -u root create simple_development

mysqladmin -u root create simple_test

create our databases – if this were a longer tutorial, we’d test it as we went.

rake rails:freeze:edge

Make your project use the latest version of rails “Edge”. You have to do this if you want to follow along. In the future, this step will be unnecessary

script/generate model Person

Our example object – a Person
[source:ruby]
db/migrate/001_create_people.rb:
class CreatePeople < ActiveRecord::Migration
def self.up
create_table :people do |t|
t.column "name", :string
t.column "bio", :text
end
end

def self.down
drop_table :people
end
end
[/source]

rake db:migrate

We’re creating our table now using a migration. If everything went well, you’ll now have a table in your database – “people”, with two columns, name and bio.

Add the following line to your config/routes.rb

map.resources :people

(this is a change from simply_restful, plural now) Here is where the magic happens. This one line of code will give you a bunch of stuff. All the mappings between REST and your controller will now just work.

script/generate controller people index new create show edit update destroy

Create our controller with all the REST / rails actions.

app/controllers/people_controller.rb:

Here’s a lot of code. This is the person controller and all the actions that you want to do on a person. They map to HTTP verbs very nicely. You should type the code (the generator made a lot if it for you, you just need to fill in the methods)

You’ll notice the funny “respond_to do |format|” stuff. This is one of the other slick features: you can send the client the format they want. So if someone were to request /person/1.xml – they clearly want xml output – this handles that (and so much more).

That was all fine and good. We could write a very nice test suite for all the code to now and still be lost on the views. Let’s go through them quickly.

app/views/people/index.rhtml

app/views/people/new.rhtml

app/views/people/show.rhtml

app/views/people/edit.rhtml

app/views/people/_form.rhtml

This concludes the whirlwind tour of the new RESTful Rails controllers.
I’ll be changing this post a lot based on feedback, so check back.

The most important things I learned about Rails development from RailsConf and RailsDay

I was fortunate enough to attend Rails Conf 2006, held between 6/23 and 6/25 in Chicago. I also participated in RailsDay 2006 on June 17th.
I’ve had a very edifying few weeks. I’m going to take a few minutes and enumerate (get it?) some of the bigger lessons learned:

  1. Know your problem domain.
    This has to be my biggest stumbling block. I’m all about going into development, guns blazing and worry about the big picture later. This is a mistake in the Rails’ world of convention over configuration. If you take some time in the beginning to figure out what models you’re going to need and how they interact with each other, you’ll be much much better off.

  2. Put as much functionality into your models as you can.
    Models are for your Business Logic. That concept escaped me until RailsDay (and even more so at RailsConf). In simple terms, you should be able to interact with your application from script/console and still have it follow the rules for your specific area.

  3. Let Rails do it’s thing and get out your way.
    This one was more from Martin Fowler’s keynote then anything. What Rails gives you is the ability to not worry so much about the “plumbing” of your app, and focus on what makes your problem domain interesting and unique.

  4. Don’t worry about the Rails Way, just get it out there and itterate!
    I heard more then once, “But I want to know the Rails Way of doing it”. I’ve felt that MANY times, and I’m giving up. This is the worst kind of analysis paralysis. Just get it out there so you can work on something real and formed.

  5. Testing isn’t scary!
    This was HUGE for me. I never tested because I thought it was hard and scary. During my RailsDay project (My one goal), I decided to just go for it with testing. You know what I found? It’s EASY. That plus Mike Clark’s Panel really taught me not only the ease of testing, but the utility. Here’s a side story, I just moved my app from Text Drive to my local server. It wasn’t working at all, so I decided to give my out of date tests a run (I gave up TDD at about 7pm on RailsDay), a LOT of them failed. It took some time to get them running, but now it works better. And each bug report that goes in gets a test case before it’s fixed.

  6. Everything is CRUD
    This was a big part of DHH’s keynote. It was hotly debated afterwards, but regardless, it’s an interesting way to look at how you set up your application. The gist is this: most of your controllers should JUST do CRUD, and if you think that a controller can’t (like a login), maybe it can. And by reframing your problem in this way, problems just go away some times. I haven’t been able to try this out yet, but I’m looking forward to it.

  7. Nobody does it right the first time
    This goes back to point 4. Basecamp didn’t spring-forth fully formed. Scott Raymond is still tweaking the “done” iconbuffet. What amazes me is that not only do all these apps keep getting bug-fixes, but developers actively go back and make their code “prettier”, which brings me to my final point

  8. Beauty matters
    When you craft your code (even if it’s not the first iteration of it) to be pleasing to you, not only are you more willing to go back and work on it, but you’re more likely to be able to bring someone new into the project. And you’ll feel better about the whole process.

  9. Shoulder Surfing is way underrated
    I was able to watch Amy Hoy and Scott Raymond work “live”. Amy was working on a design comp (whom received it right there over irc – AGILE!). Scott was doing Rails work. I have to say that those two experiences were huge for me. I’d like to see a panel next year of just live coding with breaks for questions. Between learning editor shortcuts, Rails and Ruby idioms and how some people “flow”, I think more can be conveyed then any text, video or talk can. Watching someone do what they do live is a very wide band. So thanks to both of you!

RailsConf: Things I’ve learned

Here’s a list of stuff I’ve learned and pointers to cool stuff.

RailsConf Panel: Selling Music in the 21st Century with Ben Curtis

!http://static.flickr.com/45/174612466_dc75eb189b_m.jpg!:http://flickr.com/photos/kastner/174612466/

Ben Curtis runs the plugin directory on rails

21st music is trying to fill the gap between 100% independent and 100% soul-sucking RIAA.
Ben’s major role was in making the shopping cart e-commerce site.

h3. Who is Ben Curtis?

* a startup guru
* worked at real networks
* worked at upscale USA (perl and php)
* March of ’05 he learned about Rails
* He’s not the Dell guy – even though they have the same name
* Also not the pro golfer
* “bencurtis.com”:http://bencurtis.com
* “agilewebdevelopment.com”:http://agilewebdevelopment.com
* “tesly.com”:http://tesly.com
* stympy on #ror

h4. He wrote a book – “http://www.agilewebdevelopment.com/book”:http://www.agilewebdevelopment.com/book

h3. Why build a store?

* Because you’d be out of a job if you told your client to just use Shopify!
* It’s hard.
* Do NOT build one of you want to sell one product tomorrow – use Shopify or PayPal
* But if you hate all the OSS ones, and need a real cart, write your own
* BoxCart is a Rails cart
* If you have specific business rules

h4. “It’s Just” – but it’s really not.

Ben thought it was going to be easier then it actually was.

Issues
* inventory
* attributes
* options
* payment methods
* shipping methods
* refunds
* affialiates

CDBaby and 21st both thought it would be easier then it actually was!
21st is some where around 6,000 LOC

Your client needs to do work for you! Product shots, product info, shipping info, etc etc.
Don’t forget your SSL cert.
Site design takes work also.

h4. Products and Variants

!http://static.flickr.com/53/174627666_1da2d949d6_m.jpg!:http://flickr.com/photos/kastner/174627666/

Make sure you have to write the cart.
Put all your business logic in your models!

h4. Payment Processing

TrustCommerce.com – Ben says they’re great.
PayPal’s API doesn’t like ruby (SOAP4R)
ActiveMerchant? (what is this?)

h3. Sensitive Data

* Objective: speedy check out for customer
* Problem: CC data is a liability
* Solution: Pass the buck
* Alternate solution: Encryption

h3. Gift Certificates suck.

h3. Working with Sales

h3. Taxes

h3. Returns and Refunds also suck

h3. Shipping – it’s a big deal.

h3. Affiliates

h3. Testing – DO IT and use Mocks with it

RailsConf Panel: Open Laszlo with Mike Pence

!http://static.flickr.com/71/174516202_d32c95948f_m.jpg!:http://flickr.com/photos/kastner/174516202/

“Laszlo on Rails”:http://wiki.openlaszlo.org/Laszlo_On_Rails

“http://mikepence.wordpress.com”:http://mikepence.wordpress.com

OpenLaszlo is blurring the line between desktop and web apps.
On the internet today, there is a movement towards a better look, feel and more interactivity.
Pimp my site (mypace, et. al).

Brookers from youtube demo :)

Web apps need Sex, Drugs and rock and roll which is a fun way of saying Pretty, Immersive and Rich.

Pandora is written in Laszlo.

Lzx is laszlo’s language. Kind of like XUL for Mozilla. It uses declarative XML.

Can I edit lzx in my favorite editor?

h4. Databinding

XML, even with remote http. Uses XPATH to access nodes and collections.

(And now a group hug for those of us who hate flash)

There is also a DHTML runtime, so you don’t have to worry about flash.

“openlaszlo.org”:http://openlaszlo.org

Demo of LZPics – a Flickr viewer in DHTML by way of Laszlo. Very cool and responsive.

“gliphy.com”:http://gliphy.com/

BlogBoxes are a way to give users a widget to take with them – to MySpace or wherever!

Not all roses – resources, searching and others aren’t the best. But there is a accessibility API.

RailsConf Keynote: David Heinimer Hanson

Short Version: Think before you code. If you think clearly about your domain problem – the answer is much simpler.

!http://static.flickr.com/66/174165944_3e34fa58a3_m.jpg!:http://flickr.com/photos/kastner/174165944/

Before DHH’s keynote, rails conf 2007 was announced:

RailsConf 2007 will be done in partnership with O’Reilly & Associates!
may 17th-20th in Portland, OR

DHH talks about his very strong opinions. About bending the outside world to our way, not the other way around.

In “The Real World” You’re weighed down by decades of practices.

The Japanese version of Agile Web Dev sold over 7,000 copies in the first few weeks.

43 Things does 3.5 million rails page views a day now.

h3. Create Read Update Delete (CRUD!)

It is the baseline of most of the work we do in the Rails world.
What they told you about CRUD:
* Simplistic
* Unfulfilling
* Unworthy
* Shameful

but *THEY WERE WRONG*

h3. “How I learned to stop worrying and love the CRUD”

His old way of doing things

POST /people/create
GET /people/show/1
POST /people/update/1
POST /people/destroy/1

This makes him queasy now
His new ideal:

POST /people
GET /people/1
PUT /people/1
DELETE /people/1

The problem with the new way is, even though it’s part of the HTTP Spec, it doesn’t translate well to HTML.

ActionController::Routing::Routes.draw do |map|
map.resources 'person'
end

Rails is all about making a magical world where things just apply – like mapping HTTP verbs not used very much. Even though HTML doesn’t do it, RAILS does (1.2)!

By using a hidden value, @:method => :put@ becomes @input type=”hidden” name=”_method” value=”put”@.

h4. Why Bother?

It’s a lot of work. Why should Rails go through all the trouble of making this work right?

Reasons:
* Consistency
Some of DHH’s code for controllers are a bit of a mess. Sprawling is the right word.
The more decisions you can take out, the more you can get done.
* Simplicity
* Discoverability

h4. Constraints are liberating

The real power of crud is building our your DSL(Domain Specific Language)
With the new ideas – you can do many to many’s for free. Updates, etc.

Which gets us to “Memberships”

h3. “If you want to indulge in insanity, it should HURT” – DHH.

h3. CRUD is not a goal, it’s an apiration – a design technique.

15 actions in a controller is way too many.

h3. Simply RESTful

by using the extension of the request, you can “force” mime-types. Not just for GETs but POSTs as well

h3. Active Resource

RailsConf Panel: Homesteading: A Thriver’s Guide with Nathaniel Tallbot

!http://static.flickr.com/77/174086298_dcced1f566_m.jpg!:http://flickr.com/photos/kastner/174086298/

h3. Train

c.1870 Bobby – a shop manager. Knows the ins-and-outs of the shop, but doesn’t own it. He is starting to hear things about the new frontier and how much opportunity is out there. Also, the homesteading act has just come into being (about 10 years previously). The homesteading act was the ability to stake off a large plot of land (400 or so acres), if you lived on it for 4 years and built a house the land was yours, free and clear.

In the 21st century, Homesteading is building small, sustainable business that we own (or own a piece of them).

The Train part of the talk is about why you SHOULD go out and do your own thing. Opportunity cost is how much it would cost to move on to the next thing. Some of which are not monetary. Learning, quality-of-life etc.

Live as risk management. Everyone has risk, and risk is tied to time. The amount of certainty is inversely relational to time, the longer the time, the less is known about what’s going to happen.

You only get to choose what you do right now. But what you do right now will affect what options you have in the future.

The one point to take away is that we are ALL at risk. Make sure you admit them, and weigh them out.

h3. Land

Bobby does some research. He bought the ticket, and his ticket is all the way to the west coast. Does some research on figuring out where he’s gonna stop along the way.

Figure out where you are, figure out what tools and actions you need to get there.

h3. Sunrise

Time management.
Time is our biggest non-reneable resource

h3. Community

On the frontier without other people, you’re in big trouble.
Good fences make good neighbors. Set rules and boundaries.

h3. Tools

Plowing the field is hard without an ox.

Internal and external tools – basecamp, iconbuffet, your private tools, websites, etc.

h3. Sunday

Bobby, even though he worked his butt off, still rested on sundays.

Rest allows us to do more.

h3. Inheritance

What is the value of what Bobby is doing? He is creating not only for himself, but for his future generations.

Wealth is more then monetary.

h3. Love

after 5 years, Bobby looks back and recognizes how great it is!

h3. Weather

Stuff you can’t control, but need to react to.

h4. Death

Bobby’s dead (well, he never really existed.)

h4. Buy The Ticket

RailsConf Panel: Testing Rails apps with Mike Clark

A awesome panel. Nice and slow!

h3. Unit tests

* go with one model

validates_presence_of :title
validates_uniqueness_of :title
protected
def validate
errors.add(:price, "should be positive") if price.nil? || price > 0
end

Our test

def test_validate
product = Product.new

assert !product.valid
assert product.errors.invalid?(:title)
assert product.errors.invalid?(:price)

product.title = "Something cool"
price.price = 1234
assert product.valid?, product.errors.full_messages
end

(you can run tests from TextMate!)
Same for postive checking @def test_price_should_be_positive@

To test for uniqueness, we need some data

h4. Fixtures

YAML by default – one per model.
They are eval’d by erb

price: < %= ([1,2,3,4].map &1.method(:+)).join %>


fixtures :products
def test_unique_title
product = Product.new(copy!)
assert_equal ActiveRecord::Erors.default_error_messages[:taken]
end

with fixtures, it loads the data, isolates it in a commit, then rolls it back so each test is atomic (new on 1.1)

h3. Functional Tests

You need to figure out what to test – good test cases
Again, you should use your fixtures in your functionals

fixtures :users
def test_good_login
dave = users(:dave)
post :login, :name => dave.anme, :pasword => 'secret'
assert that it worked
end

RailsConf Panel: Universal design

h3. What is universal design?

Getting your design to the WIDEST range possible as is viable in busines

h4. Accessiblity is for

* people with disabilities
* sensory
* motor
* cognitive

h4. people with technical or cultural disadvantages

* Old computers or slow internet connections
* English as a second language

h4. Accessible tech

h4. Nielsen in usability engineering cites 5 factors:

* Learnablity
* Efficiency
* memoraiblity
* errors
* satisfaction

h4. Epicenter design

* 37signals
“Start from the core of the page”
* Microsoft

h4. Steve Krug’s Trunk test

If I took a user out of a trunk, will they understand it?

* What site is this
* What is this site for
* …4 more

h4. Tog’s First principals

Fitt’s law – the closer and bigger the target is, the easier it is to hit.

h3. Why is Accesibility important

* laws
* by 2020 estimates are 40 million americans will have a visual disabillity

h3. How do we accomodate users?

* Sensory – Standars XHTML+CSS. Transcriptions of podcasts and movies
* Motor – assistive hardare
* Cognitive – not much we can do.
* Cultural – page optimization, alt text (if they turn off images), etc. / standardized access keys etc.