Posts Tagged ‘rails’

Fixing the “You have to install development tools first” error with Nokogiri.

Friday, November 26th, 2010

After wracking my brains around a strange issue installing Nokogiri, wmoxam in #rubyonrails and I figured out how to get it to install.

Problem: You go to install nokogiri, either with bundler or with a straight “gem install nokogiri”, and you get an error like the following:

In your wisdom, you decide to jump over to Aaron Paterson’s Installing Nokogiri page, where he tells you to install the libs, libxml2 and libxslt, manually and configure the gem install to those libs with flags … but it still doesn’t work.

Solution: You are probably using RVM, right? Yeah, we’ll when you installed ruby 1.9.* with it, it was probably old. Update your rvm install and re-install ruby with the new RVM version, and you will be green.

1
2
3
4
5
6
7
8
rvm update head
rvm --force install 1.9.2
gem install bundle

## in your rails app
bundle
Installing nokogiri (1.4.2) with native extensions
 ...

Boom!

Tags: , ,
Posted in Information | 12 Comments »

ReadOnly needs to be set to true or false, not :true or :false

Thursday, November 18th, 2010

Just taking some time to let you in on another gotcha. Hopefully, this saves people some aggravation some day.

While working on Kludge, we took a RESTful approach and built our controller like so:

1
2
3
4
5
class ProjectsController < ApplicationController
  def update
    @project = Project.find(params[:id]).update_attributes(params[:project])
  end
end

While this works, it doesn’t offer you any protection that evil users may try to update projects that don’t belong to them. A better approach is to scope the projects to that belong to the account. So we updated the action to the following:

1
2
3
4
5
class ProjectsController < ApplicationController
  def update
    @project = current_account.projects.find(params[:id]).update_attributes(params[:project])
  end
end

…and we got an error!

1
2
ActiveRecord::ReadOnlyRecord (ActiveRecord::ReadOnlyRecord):
  app/controllers/projects_controller.rb:45:in `update'

This error arises because Rails makes all associations read-only. Since projects is now an association to account, we need to force readonly to false in the account model:

1
2
3
4
class Account < ActiveRecord::Base
  has_many :clients
  has_many :projects, :through => :clients, :readonly => :false
end

However, this will still throw the same error message! After googling, IRC-ing, and crying … I finally got the answer through brute-force trial and error. Turns out, :readonly does not accept the symbol :false, and only the literal false. Changing the following will make your test green:

1
2
3
4
class Account < ActiveRecord::Base
  has_many :clients
  has_many :projects, :through => :clients, :readonly => false # <-- no longer a symbol
end

Tags: ,
Posted in Code | 2 Comments »

Getting Comfortable Working With Rails Core

Sunday, August 15th, 2010

This year’s RailsConf was truly one of the most impressive and inspiring development conferences I have ever been to. Bright-eyed and bewildered, I got to listen to lectures from people big and small in the community. Two individuals, in particular, stood out to me: Yehuda Katz and Rick Martinez. I listened to Yehuda’s keynote; the now Rails hero’s mentioned in his talk “I was just some guy who dove in, and here I am.” Rick Martinez of Flavorpill.com, who you may not know, is really just a guy who did dive in and was able to give a fascinating talk called “Hardcore Extending Rails 3.” The overall message? Again, “I just started digging around, and here’s what I came up with.”

As an aside, one of the questioneers at Rick’s talk was Yehuda commenting something to the affect of “this is what we wish more people would do, just dive in.”

I knew I had what it takes to dive in, it was just a matter of discipline and taking the time to learn the tools and get acclimated with the libraries. I walked into the conference feeling like a novice about to hear four days of lectures that were way over my head, and I left chomping at the bit waiting to start tearing to guts of Rails 3 wide open (which I began to do the entire trainride home).

For the past two months since then, I’ve been consuming more Ruby information then ever, determined to master the language and become a productive member of the Rails community. There have been frustrating times when I didn’t understand anything (and there will be more of that to come), but there has also been a wealth of knowledge that I have gained and have been able to apply immediately. For those of you who want to dive in, I’ve assembled this list of things I’ve done to get going and I think it could help you out, too. Pick and choose as you wish; these items may not all be for you, but if it’s on this list, it’s because I directly associate it with my growth.

  • Read The Ruby 1.9 Book

    If you want to work with Rails, you have got to learn Ruby. Ruby is filled with new concepts and techniques that you probably haven’t experienced in other languages. The more of this language you know, the more you will understand the design patterns that the Rails library uses, and the more power you can leverage in your own code. The internal architecture of the code is a lot to take in, you don’t want to be hung up on Ruby syntax at the same time. Learning Ruby will help you separate whether what you are looking at is confusing because of your lack of understanding of the Ruby code or the Rails library (looking at the Rails lib after learning Ruby better, the code is so much easier to follow). Read “The Ruby 1.9 Book,” also known as “The Pickaxe Book.”

  • Learn Ruby Metaprogramming

    Metaprogramming is the practice of writing code that writes code. Two weeks ago, I would have told you that Metaprogramming is something that the pros did because they’ve grown so bored with the boundaries of the language that they want to add to it. On the contrary, metaprogramming is a staple of working with Ruby and is a compliment of the language’s aesthetics. Learning about concepts such as Open Classes, Dynamic Dispatch and Methods, and beyond will help you understand how programmers wrangle Ruby to get it to work the way they want it to.

    Here are three great resources resource for learning Ruby metaprogramming:

    1. “The Ruby 1.9 Book” book has entire chapter on metaprogramming. I recommend reading this before jumping into…
    2. “Ruby Metaprogramming” by Paolo Perrotta. This book explains metaprogramming concepts in a fun, observational way, with an entire section on metaprogramming Rails.
    3. As a follow up, Yehuda wrote an article that helps clear up some common misconceptions about how to properly write libraries – “Metaprogramming In Ruby”

    By now you realize you’ve got a lot of reading to do, which is why I totally recommend that you…

  • Buy an iPad

    This may seem like one of those “you-got-to-be-kidding-me” kind of todos. But the truth is, I single-handedly attribute so much of my educational growth over the past month to me buying the iPad. Last year, I bought the Ruby 1.9 book and the PDF. The book sat on my shelf and I only casually browsed through it. The PDF was on my laptop, and I only fired it up a couple of times, and then get distracted by a client’s email, or a blog post, and ultimately didn’t read any of it. With the iPad, I take it everywhere: I read for 15 minutes at the laundry mat, 30 minutes at then pool, before I go to sleep, etc. In three weeks, I read over 450 pages of the Ruby 1.9 book and over 250 pages of the Metaprogramming book. Here is the key though: make it an educational device only. For me, that meant not loading on a Facebook app or any other distractions, I didn’t even configure my mail account or add music to it. It’s simply there for ebook reading, reading RSS feeds and Tweets from other developers, and writing blog posts. It’s a productivity machine!

  • Read the Rails source code

    While it may seem daunting at first, the current version of the Rails 3 library is one of the most elegant codebases to try and follow. Before taking the plunge into the codebase myself, I used to hear people say “look at the source” and I used to think “I am not at that level yet.” Trust me, you are, and the more comfortable you get with Ruby, the more you will learn how the Rails code plays into it’s strengths. Additionally, the library is filled with extremely helpful comments. For example, check out base.rb in ActiveRecord; don’t quote me on this, but I’m pretty sure for every line of code, there are two or three lines of comments.

  • Get Involved

    When it comes to getting involved with Rails, you couldn’t ask for a better community to help you out then the Rails community. There are people with all different levels of expertise, willing to lend a hand to help you achieve whatever you’re trying to accomplish.

    • Go to conferences and meet ups. Not only do you learn about emerging technologies, but you also get to network and make friends with other developers, as well as learn about other popular developers in the community. One key piece of advice: don’t be shy. Everyone is there for the same reason, and everyone I’ve gotten to meet in the Ruby community have been nothing but nice and helpful.
    • The Ruby on Rails IRC on freenode, #rubyonrails. Don’t feel shy; just ask your question and be patient. Feel free to hit me up in there, I’d be more than happy to help you out.
    • RailsBridge – RailsBridge is a group of people committed to helping you learn more about Rails. They can answer your questions in the #railsbridge IRC, they organize weekend bug mashes to help the Rails core team get through ticket issues in Lighthouse, and are really just a great group of people. I got to spend a good half hour chatting with Santiago Pastorino of WyeWorks at RailsConf, about RailsBridge and all the things they do, awesome stuff!
    • Read up on the work other developers are up to. Guys like Aaron Paterson, Ilya Gregorik, and Yehuda Katz will commonly blog or tweet about things they are working on. You can learn a lot by being a fly on the wall.

    The biggest piece of advice I can give you in terms of getting involved with the Rails codebase is: start. Any new library takes time to learn, and Rails is no exception. If you follow any or all of the tips I’ve listed, I think you’ll find the learning curve to be a little less steep. If you have any other advice that helped you out along to way, please leave a comment below, myself and others would appreciate it.

    Tags:
    Posted in Lecture | 4 Comments »

‘Mail’ is a resevered model name in Rails 3

Monday, July 19th, 2010

This may bite you in the ass if you are upgrading a Rails app from 2 to 3: ‘Mail’ is now a reserved model name. That means, if you currently have a model app/models/mail.rb, and/or a class defined as class Mail < AR::Base (for instance), it will collide with the new Mail class in Rails 3, and possibly throw this error

1
undefined method `transfer_encoding' for class `Mail::Message'

That is because Rails defines Mail.transfer_encoding in it’s Mail class, and your’s is over-riding it. The quick fix: rename your class and your file name.

Tags:
Posted in Code | No Comments »

Working With Rack in Rails 3

Thursday, June 10th, 2010

While attending this year’s RailsConf in Baltimore, there was much excitement in the air about Rails 3. This was perpetuated by the fact that the Rails core team pushed Rails 3, Beta 3 & 4 during the conference. While there are so many awesome new things that Rails 3 is providing, and I strongly encourage everyone to move over to it as soon as they can, I want to talk today about Rack, and how it is allowing your to optimize your Rails app like never before.

Nice Rack.

If you are new to a lot of the things going on in Rails 3, you probably aren’t to familiar with the concept of Rack. The story goes like this: before Rails 3, all of the things that the Rails framework provides you, like session handling, parsing the parameters, and other conveniences that Rails provides you pertaining to requests, were tightly coupled to the Rails code base. In the early days of Rails, this was no big deal; we had these tools and we loved them. However, as Rails grew, and the apps built on Rails had more demanding requirements, we found situations where these conveniences add a lot of not needed overhead. For example, let’s say we wanted to have a Rails application whose sole responsibility was to accept uploaded files that we save to a server. You wouldn’t necessarily need session handling, cookies, flash, etc. Also, you may have written a great library that is better optimized or offers more hooks to certain ingrained Rails functionality for your application that you would like to use instead. Enter Rails 3.

In Rails 3, the framework gutted many of these great features out of the framework and into this concept of a Rack. We’ll talk about what Rack is in just a second, but it is important to note that the key advantage hear is that these awesome conveniences can be taken out of your application stack (or enhanced) to optimize them to suite your application’s need.

Anatomy of a Rack

Ok, ok … so what is a Rack? Rack is simply an interface that sits in between your web server and your application.


When a request comes into a Rails app, before it encounters your application code, it will run through your Rack. The rack is a daisy-chained library of classes, each of which have different responsibilities, all of which are the dominant set-ups that need to be done for every request (sessions, params, etc).

Components

A Rack application is simply a class which defines a method, #call. This method receives a parameter, the current set up environment hash, commonly named “env”. The required return value of that method is an array composed of exactly three elements:

  • The status code (200, 404, etc.)
  • The headers for the request
  • The response body

Note: The response body must respond to #each, therefore you will commonly find it in an array ( [my_response]) or a class mixed in with Enumerable.

The next Rack application inline to fire in your middleware will make a call to #call when it initializes and will receive its return value (the response / header / body array) as a parameter to #initialize, commonly labeled “app”.

Enough talking, let’s looks at code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
module Rack

  # The Rack::Static middleware intercepts requests for static files
  # (javascript files, images, stylesheets, etc) based on the url prefixes
  # passed in the options, and serves them using a Rack::File object. This
  # allows a Rack stack to serve both static and dynamic content.
  #
  # Examples:
  #     use Rack::Static, :urls => ["/media"]
  #     will serve all requests beginning with /media from the "media" folder
  #     located in the current directory (ie media/*).
  #
  #     use Rack::Static, :urls => ["/css", "/images"], :root => "public"
  #     will serve all requests beginning with /css or /images from the folder
  #     "public" in the current directory (ie public/css/* and public/images/*)

  class Static

    def initialize(app, options={})
      @app = app
      @urls = options[:urls] || ["/favicon.ico"]
      root = options[:root] || Dir.pwd
      @file_server = Rack::File.new(root)
    end

    def call(env)
      path = env["PATH_INFO"]
      can_serve = @urls.any? { |url| path.index(url) == 0 }

      if can_serve
        @file_server.call(env)
      else
        @app.call(env)
      end
    end

  end
end

So here is the first Rack application in a default Rails 3 stack, which is responsible for serving back static files. As you can see, it’s #initialize receives “app” as a first parameter, which would be the response of #call from the previous Rack app. For this Rack, the #call function doesn’t create it’s own array to return, it simply loads a static file if it finds it with Rack::File, or just passes the current environment silently if there is no static file.

Closing

The best way to learn what rack can do for you is to look into the code for the current Rails 3 stack and see what it does. You can get a list of your rack stack by running:

1
rake middleware

See also the Official Rack Project site for super easy documentation and explanations.

Tags: ,
Posted in Code | No Comments »

Adding Methods on Associations in Rails

Wednesday, February 17th, 2010

Many times, you may find yourself interested in moving some of your logic outside of the view and into a model, so that you can re-use it throughout your app. But sometimes, the method you may want to define needs to be on an association of two models, and not on the models themselves.

As a real world scenario, imagine you are making an online game in which two models exist, Game and Score. The Game model keeps track of when the game was started, who started it, the level of difficulty, etc. The Score model keeps track of the value of the score, the round the score was done in, and the time the score was placed. The Game model has many Score models. Obviously, when the game is over, we are going to want to be able to see the total score. But what model do we define the method on? The Game model, itself, doesn’t have any scores and a Score object only knows about itself and not all the others that belong to the parent Game object.

This is a situation where the method needs to be defined on the association of Game and Score. Anytime the value you are trying to obtain can only be calculated with a parent and a child of an association, then you need to define the method on the association.

How to define it

Turns out that defining the method is a little trivial. The has_many method, used for creating one-to-many relationships, accepts a block in which you can define methods. Inside that block, self is set to the collection of children in the relationship. So now to define your total_score method:

1
2
3
4
5
6
7
8
9
  class Game < ActiveRecord::Base
    has_many :scores do
      def total_score
          total = 0
          self.each { |score| total += score.value }
          total
      end
    end
  end

Then, in the app …

1
2
3
4
5
6
7
g = Game.create(:user_id => 1)
g.scores.build(:value=>20)
g.scores.build(:value=>40)
g.scores.build(:value=>60)
g.save
g.scores.total_score
# 120

Tags: , ,
Posted in Code | 2 Comments »

Installing Ruby 1.9, Rails 2.3.5 and Getting RSpec/Cucumber working on Mac

Thursday, December 31st, 2009

There was a little bit of jumping around to figure this all of, so I figured I’d put it all in one place here

Installing Ruby 1.9

  • Download and Unpackage Ruby from http://www.ruby-lang.org/en/downloads/, the cd into the dir
  • Run `autoconf`
  • Run `./configure –enable-shared –with-readline-dir=/usr/local`
  • Run `make && sudo make install`
  • Add /usr/local/bin to $PATH (most likely in ~/.profile or ~/.bash_profile)
  • Run `ruby -v` and ensure it now says version 1.9.1

Installing Gems

sudo gem install -v=2.3.5 rails sqlite3-ruby rspec-rails cucumber-rails webrat -v=1.2.3 test-unit database_cleaner

Loading RSpec and Cucumber

In your app..

script/generate rspec
script/generate cucumber

Then open features/support/env.rb and comment out line #18 to remove warning when you run cucumber
You should be all set, if not, leave me a comment – I’ll be pretty quick about responding to them.

Tags:
Posted in Code | No Comments »

Update Child Model From Parent’s Attributes in Rails

Wednesday, December 23rd, 2009

You probably already know that you can add child models relationships through the parent model once you have set up your models appropriately:

BlogPost < ActiveRecord::Base
  has_many :comments
end

Comment < ActiveRecord::Base
  belongs_to :blogpost
end

..and then you can do something like:

@blog = BlogPost.new(:title => "My First Post")
@comment = Comment.new(:body => "Great Post!")
@blog << @comment
@blog.save

We use the << method to make a foreign key relationship. When we save the blogpost model, it automagically saves the @comment model, and associates it with blogpost record via a foreign key, so that we can later say

puts @blog.comment.first.body
# "Great Post!"

But, what you may have not known about is Nested Attributes. This is a slick little feature, turned off by default, that allows you to create the child model via parameters of the parent model. To enable it, simply add this method call to the parent model:

BlogPost < ActiveRecord::Base
  has_many :comments

  accepts_nested_attributes_for :comments
end

Now, you can create the same blog/comment models & relationship with a quicker syntax:

@blog = BlogPost.new(:name => "My First Post", :comments_attributes => [{ :body => "Great Post!" }])
@blog.save

Upon saving, this will create the BlogPost, create the Comment, and set up the foreign key relationship. Sick!

To learn more, check out: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Tags:
Posted in Code | No Comments »

Ruby on Rails May Become Really Popular Soon.

Saturday, December 5th, 2009

I found this and I just thought it was too adorable not to repost: http://37signals.com/svn/archives/000606.php

Tags: ,
Posted in Uncategorized | No Comments »