Rails Coach show

Rails Coach

Summary: A series of short discussions on topics related to Ruby and Rails. Topics range from basic Ruby and Rails concepts to advanced topics.

Join Now to Subscribe to this Podcast
  • Visit Website
  • RSS
  • Artist: Charles Max Wood
  • Copyright: (c) Intentional Excellence Productions LLC

Podcasts:

 Rails Controllers: Before, After, and Around Filters | File Type: audio/mpeg | Duration: 7:15

In your Rails controllers you have filters you can place on incoming requests, outgoing responses, or wrap around your actions. Before filters are run on requests before the request gets to the controller’s action. It can return a response itself and completely bypass the action. The most common use of before filters is validating a user’s authentication before granting them access to the action designated to handle their request. I’ve also seen them used to load a resource from the database, check permissions on a resource, or manage redirects under other circumstances. After filters are run after the action completes. It can modify the response. Most of the time if something is done in an after filter, it can be done in the action itself, but if there is some logic to be run after running any of a set of actions, then an after filter is a good place to do it. Generally, I’ve seen after and around filters used for logging. Around filters may have logic before and after the action being run. It simply yields to the action in whatever place is necessary. Note that it doesn’t need to yield to the action and may run without doing so like a before filter. You can use around filters for exception handling, setup and teardown, and a myriad of other cases.

 ActiveRecord Callbacks | File Type: audio/mpeg | Duration: 8:14

You can get a full list of the ActiveRecord callbacks here. Callbacks are a handy way of insuring specific behaviors on your models as well as managing the events that follow the callbacks. For example, a before_destroy callback can be called to destroy associated objects. (This is best done on the association with :dependent => :destroy, but it makes sense here too.) You can also stop the destroy process if you have dependent objects you can’t destroy by returning false. I’ve used ActiveRecord Callbacks to: Set default values Format specific fields (like phone numbers) Send emails when an object is updated or deleted Create child objects from comma delimited lists in a string Change an object’s state

 The DRY Principle | File Type: audio/mpeg | Duration: 7:43

According to The Pragmatic Programmer by Andy Hunt and Dave Thomas, "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." Last week I talked about extending your Ruby on Rails application. This is because in many cases in order to avoid repeating your logic across multiple classes (models or controllers) you need another place to put your functionality. Mix-in modules, plugins, and single table inheritance all allow you to codify your knowledge into a single place depending on what you’re working with. The DRY principle is more than just a way to avoid having to update multiple files when something changes. Rather, it’s a way of assuring yourself that things are done in a consistent manner. It also helps you when you’re trying to find something in your application because there’s only one place where it can be found.

 Extending Ruby on Rails | File Type: audio/mpeg | Duration: 9:53

I’m going to be talking about the DRY principle next week. However, before I jump into that, I need to discuss how to extend Ruby on Rails so you know where you can put functionality to keep your application DRY. There are a couple of standard places people put code that isn’t a Model, View, Controller, or Helper: The ‘lib’ folder - This is sort of a “junk drawer” for your application. In Rails 3 your application does not load these files on its own. You can make it autoload by following the directions I found on StackOverflow. Rails Plugins - Rails Plugins are autoloaded by your Rails applications and can contain extensions to Models, Views, Controllers, Helpers, and to the app as a whole through Engines. Ruby Gems - Gems can do pretty much anything Plugins can do except they are not included in your application’s source. They are pulled in through Bundler. You can also add modules and classes to files within the app directory.

 Rails’ Component Libraries | File Type: audio/mpeg | Duration: 9:54

Rails is made up of several components that all have specific jobs in making your Rails application work. Here’s a quick list of what they are and what they do. ActionMailer - The basis for mailers. This is the library that allows you to format and send emails from your rails application ActionPack - The components that parse, delegate, and render responses for requests. ActionDispatch - Parses HTTP requests and sends the requests to controllers. ActionController - Basis for Controllers -Takes requests and request parameters and gathers data to render a response. ActionView - Basis for Views. Determines which template to use and builds the response to the HTTP request from the templates based on data provided by the Controller. ActiveModel - Defines an interface on non-ActiveRecord classes that helps the behave like ActiveRecord models. ActiveRecord - Basis for Models. Manages the connection between the Rails application and a SQL database. Provides means of querying database to manage and find records. ActiveResource - Allows the developer to access network REST resources in a simple way. ActiveSupport - A collection of extensions to the Ruby programming language that can be used in your Ruby on Rails application. You can read in more detail what these libraries are about and what they do on the Ruby on Rails github page.

 Debugging | File Type: audio/mpeg | Duration: 8:21

We talked quite a bit today about debugging tools in the Ruby Rogues podcast. I recorded this before that episode. Here's a brief introduction on how to use debuggers to find problems in your Rails code. The basic idea is that your set a breakpoint in your application, which causes the application to stop processing and allow you to access the application's state and step through the methods being called in order to find the cause of your problem. With the Ruby Debug library, all you need to do is require 'ruby-debug' and call 'debugger' where you want the application to stop.

 Convention over Configuration | File Type: audio/mpeg | Duration: 9:38

The idea behind convention over configuration is that rather than having several or one large configuration file to set up the framework for you to use, Rails uses conventions to determine how things should work without configuration. In many cases in Rails, there are ways to override the default convention, but most people stick to the conventions. The conventions make it easy to set up and get started with Ruby on Rails. They also make it extremely easy for a person unfamiliar with your Rails project to step in and figure out what is going on. Some of the conventions in Rails are the following: A model's class is the camel cased singular version of its table name. The file name is the underscore cased version of the class name. The table name is the underscore cased pluralized model name. So, for example, the User model will be /app/models/user.rb and correspond to the "users" table in the database. Similar conventions apply to controllers, helpers, views, and tests.

 Ruby on Rails Routing | File Type: audio/mpeg | Duration: 11:30

Ruby on Rails routing can be a little confusing. Here are some of the high points. The root path is specified by the 'root' method. It matches the '/' path and behaves like 'match'. The 'match' method will match the requested path to the string passed to match and route to the controller and action specified. # Sends requests to /users/list to PeopleController#index match "users/list", :to => "people#index" You can also extract variables from the path. # Matches /user/1/edit and passes '1' in params[:id] match "users/:id/edit", :to => "users#edit" You can specify which HTTP request methods are valid for a route. get "users/index" match "users/index", :to => "users#index", :via => :get You can also name a route and use the related helper methods. match "users/index", :to => "users#index", :as => "user_index" #In some controller or view user_index_path # => "/users/index" user_index_url # => "http://localhost:3000/users/index" You can also create RESTful resources around a model. See the Rails Guides for details. resource :user Finally, you can add to a RESTful resource when needed. # allows you to post to '/users/1/make_admin' and get '/users/show_admins' resource :user do post :make_admin, :on => :member get :show_admins, :on => :collection end

 Rails Engines | File Type: audio/mpeg | Duration: 9:56

Rails Engines are a terrific way of mounting on Ruby on Rails application into another. A Rails Engine is basically a Rails application with an Engine class installed. The main application—the application your engine is mounted into—uses the generators, rake tasks, and routes from engines automatically. As of Rails 3.1, rake tasks are provided to move migrations and assets into the main application. You can use Engines to add features to your current application or you can use it to provide an entire section of your website.

 009 RC RubyGems and Bundler | File Type: audio/mpeg | Duration: 13:19

Ruby has a package manager for its libraries or gems. It should be a concept familiar with other package managers like apt, yum, or yast. Gems are libraries for Ruby. Many gems are built to extend Ruby on Rails and are a great way to add functionality to your application. You can see available gems at RubyGems.org. In order to install Rails, you typically need Rubygems installed via a "gem install rails". To get a pre-release version of Rails, you can run "gem install rails --pre". Gems for use in your Rails application are included in your Gemfile. Once you've specified the gems, run "bundle" or "bundle install" to get the gems you need. You can set up a test group to include testing and debugging libraries and exclude them in production environments. Bundler handles dependency problems by evaluating dependencies and then chooses the libraries that meet all dependencies.

 008 RC ActiveRecord Migration Gotchas | File Type: audio/mpeg | Duration: 14:24

Rails Migrations are generally pretty straightforward, but there are a few things that people do that wind up giving them headaches later on. First, don't change migrations once they've been committed or deployed. This causes problems because ActiveRecord tracks migrations that have already been run. So, editing a migration that's already been run will result in your changes not being made. Second, use Rails' built in migration and model generators. It generates the id number in the front of the migration from a timestamp which minimizes that possibility of having a collision on the migration's identifier. Third, create mapping tables in your migrations so your connections work. When you do these migrations, make sure you have ":id => false" on your "create_table" call. When creating mapping tables, eliminate the meta data on the mapping unless you're using a "has_many :through =>" relationship. Adding meta fields to mapping tables will be deprecated in Rails 3.1. Fourth, add indexes to all foreign id's. Those are the "_id" columns in your tables. I've used the rails_indexes plugin for this. Fifth, don't reference Models in your migrations. If your Model implementation or attribute sets change, your migrations may no longer work. Instead, call "execute" with your SQL queries to update and save data in the database in your migrations. Finally, go check out the Ruby Rogues podcast! You can also get my interview with Tom Preston-Werner from Github here.

 007 RC Rails Authorization Basics | File Type: audio/mpeg | Duration: 11:17

Libraries for Authorization controls in Ruby on Rails are not nearly is prolific as they are with Authorization. The one I typically use is Cancan. The thing I like about Cancan is that it provides fairly granular model level controls. You have to do the checks—Rails won't do them for you—but they are fairly straightforward. The other thing I like about it is that it provides some Controller level controls through a before filter you can include that will pull up the model, load the object, and check permissions before loading the Controller action. Ideally, a good Authorization library allows this level of control at all three levels of your application.

 006 RC Ruby on Rails Authentication Basics | File Type: audio/mpeg | Duration: 15:18

In a lot of web applications, you need to control who can access your data. Authentication is the key to this type of security. Ruby on Rails has some plugins and gems that make authentication pretty easy. Here are a few: restful-authentication authlogic devise When putting authentication together, make sure that your authentication schema provides encryption for your passwords and a salt to make it more difficult for hackers to figure out which users are using the same password. Also make sure that your failed authentication messages read "Your username or password is incorrect." rather than pointing out which specific field is incorrect. This will prevent hackers from mining your usernames and trying to guess their passwords. Lost password messages should also report success every time. Since you won't be able to decrypt the passwords, you should always give a message like "An email message has been sent to you to reset your password" even if the username or email isn't in your system. Finally, to avoid problems where people are sniffing networks with tools like firesheep to get usernames, passwords, and session cookies. Make sure that you're encrypting your logins and sessions with SSL. Use the ssl_requirement plugin to take care of this for you. Here's the video: And the transcript: Rails Coach Podcast episode 6. Hey everybody and welcome back to the Rails Coach Podcast with Charles Max Wood, that’s me. This week we’re going to be talking about authentication. But before we get started I really want to talk about where things have been going with this podcast. It’s kind of been an exploratory mission for me to kind of figure out how I want to talk about Rails. The thing is that I’ve had the Teach me to Code podcast for awhile, and I really didn’t feel like once I moved it from the Rails Coach podcast to the Teach Me to Code Podcast that I could talk as deeply about Rails, and so I wanted to talk about that there. The problem is that I’ve been talking about things that I feel like are better explained through demonstration as opposed t o actually talking about principles that people should know when they’re programming in Rails. So what I’m going to do is I’m going to kind of change tactics a little bit. So I’m not going to go into as much things like; you should use this tool, you should use that tool. Well, I am, but I’m not going to go into how they’re used, I’m not going to go into what they are. What I’m going to try and do instead is I’m going to talk about general principles around certain things that are relevant to Rails. So, for example, this week I’m going to be talking about authentication, so I’ll probably bring up a few plugins or gems that you can use for authentication and I’ll talk about a few of the principles that define good practices for these different things. So in this case I'm going to be talking about authentication, and there are things that I see that people generally get right, and there a few things that I see that generally people don’t get right. I see these things, some of these things, done on these huge sites that have thousands and thousands of users and I’m flabbergasted that this is there because it’s so simple to just write a script that takes advantage of some of this stuff. And so I'm just going to jump right in on the authentication stuff. First off, I just want to talk a bit about the history of authentication with Rails. It all kind of started, as far as I can tell, with the restful-authentication plugin that was written by Rick Olson. This was probably four or five years ago. And restful-authentication took advantage of the RESTful approach that Rails had implemented at the time and proved an authentication scheme where it used the RESTful paths like GET and POST and PUT and DELETE, to manage sessions, and so sessions were the resources that the restful-authentication handled.

 005 RC Testing Tools for Rails | File Type: audio/mpeg | Duration: 13:32

There are a lot of tools for testing Rails. Here are links to several of the ones mentioned in this podcast. Test Unit RSpec Cucumber Mocha Flexmock Factory Girl You can find my interview with David Heinemeier Hansson here, and my response to his comments on Twitter here. Finally, here are a few other resources for you to get started with testing Ruby on Rails. Introduction to Outside-In Development with Cucumber Here's a transcript of the podcast: Rails Coach Podcast, Episode 5 Hey, everybody, and welcome back to another Rails Coach podcast. This is Charles Max Wood and this week we’re going to go into testing Rails. You can test Rails in a lot of different ways, and we’re going to talk about some of the libraries that are around for doing that. I’m also going to talk about my approach to it; some of the things that I’m thinking about doing or changing – and I guess we should just dive right in. First off, I want to point out that there’s been a discussion on Twitter about Test Unit vs. RSpec. Now, if you’re not familiar with Ruby on Rails or who David Heinemeier Hansson is, then I recommend that you go listen to the “Teach Me To Code” podcast. I interviewed David on that podcast and talked a little bit about Ruby on Rails. And that will give you kind of a feel for who he is. He’s the guy that wrote Ruby on Rails and he is the technical partner at 37signals that makes Basecamp and Highrise and a bunch of other products that I used to use. But I don’t anymore. And that’s not the topic for this podcast. Anyway, we’re going to go into some of the things that are available for testing Ruby on Rails. I’m going to go into, first off, the discussion that was had over RSpec and Test Unit. David Heinemeier Hansson, a while back, said that he and 37signals, they used Test Unit, and that Test Unit and Mocha, which is a mocking and stubbing framework were basically all you need for good Ruby on Rails testing. Then he later said that he was a little disappointed by the proliferation of RSpec and Cucumber because he felt like they were a little too complicated and had been cargo-culted upon the Ruby on Rails community. And that started a whole lot of discussion over whether or not RSpec and Cucumber were the right tool. There were people who came out and said, Oh yeah, David’s right. Test Unit all the way. And other people came out and said, Hey wait a minute, RSpec all the way. David, you’re an idiot. And some people had kind of the reaction that I had where we thought about it for a minute and said, I’ve been using Test Unit or RSpec for a while, and I really ought to explore what the differences are and why I might want to use one over the other. I really haven’t had a chance to do that. However, I have used both; I’ve used both on different projects. And so I think it is worth discussing testing tools that are available for Ruby on Rails and what you can do to learn this stuff. So we’ll jump right in here. First off, I use – I’ll let you know – I use RSpec and Cucumber, and I use Factory Girl to generate my objects that I am going to be testing against. And then I use FlexMark for mocking and stubbing. That’s more or less what I use. Now, with Cucumber I use Capybara. And then I’ve recently started using Culerity and Celerity to test my JavaScript. And that has been working, actually, really well. So, basically I use RSpec to do some of the testing in Cucumber. For example, you can write your assertions or dot-shoulds in Cucumber steps, and if they fail then your Cucumber scenario fails. RSpec I also use for my unit tests. And unit tests are just class-level tests. They usually use some method of mocking or stubbing to isolate your object so that you can test one way or the other, or if you have a dependent object, then you don’t necessarily have to mock that out. It’s a matter of preference as to how deeply and how thoroughly you mock things out. In my case,

 004 RC Ruby on Rails Model Validations | File Type: audio/mpeg | Duration: 12:50

You can get the video version of this podcast here. I've also updated the audio files for episodes 2 & 3 so you can hear them now. Sorry for the trouble. Ruby on Rails provides some excellent ways to validate the data you save in your models. Validations are methods called within the class definition specifying an attribute to check and what to look for. class User

Comments

Login or signup comment.