 Ruby Midwest. I'm excited to be here. I'm Michael Blye on Twitter M. Blye. I am a Kansas City native and I'm very happy to be presenting here and I was even happier when I moved back to Kansas City from living other places for a long time last year that there was such a great Ruby community in Kansas City because I didn't expect it. So thanks to all the organizers for putting this event on and the one last year and the KC Ruby Meetup group is great. So I've been really happy with that. I'm a partner at Intridia. It's a Rails consulting shop. We also build products. So I have a lot of chance to work with Ruby. And today, oh yeah, this is a nice little HTML5 slideshow so you can follow it along if you want. M. Blye.com slash Rails is the new Rails. Use deck.js to build it. That was my first experience with that. It's pretty nice. Anyway, I don't consider this to be a cool talk. So normally, when I'm submitting a talk for a conference, I'll pick some topic that is like, oh, that's really cool. I know a little bit about this. I want to learn more and I want to tell other people about it. This isn't really that talk for me. To me, this talk is more just about useful little tips. So it's just a bunch of tips. You might call this Rails Safari after Ola's Ruby Safari last talk. I think they'll actually sort of compliment each other well. He was giving you fun little things you can do with Ruby and I'm hopefully giving you some fun little things that you can do with Rails. Many of, you know, some or many of these you may already know. Some you may not. But I think that these little tricks and these little things that let you do your work faster are important. So I'm going to go into a very short little bit about that. I think for developers, time is sanity. Time as money is the traditional phrasing. But I think that as a developer, anything you can do to save yourself time to make your development easier, to make your just day-to-day workflow better just helps keep you sane, helps keep you productive. And I think that, you know, as a Ruby community, the Ruby community is incredibly good at finding all of those little tricks that make you more productive. I'd say it's a group that's almost obsessed with it. And that's one of the reasons that I love Ruby. So I recently, I'm actually, I live in Kansas City, but I'm actually living in New York right now because I'm consulting on site in New York. And I recently had the chance to sort of, you know, completely spin up a fresh development environment, come into a code base that I had, you know, zero familiarity with. And so dropping into that situation, I sort of realized, you know, how important and how much I take for granted all of these tools that I use for faster development and all these little tricks that I know in Rails. I think that building up a library of those tools is important. I think it's important to always be optimizing your workflow. I think it's important to make sure that whenever you're developing, you're not feeling, that you don't feel friction, just like frustration. Like, you know, I wish that this thing was different, but it's not. You know, if you wish that something was different about your development flow, take the time, you know, even if it's a day to fix it, you know, find out why it's that way, make it better. Because if that's something that's going to save you, you know, 30 seconds, 10 times a day, then, you know, over the weeks and months, that's going to save you a ton of time. It's going to keep your sanity and it's going to make you happier as a developer. So enough of that. And let's just go on and see some tips. So let's start with the Rails router. So the Rails 3 router, awesome rewrite, lots of new features. Something that I don't think people use a ton is routing constraints. So in Rails 3, anything can be a routing constraint. Anything that responds to call, so like a lambda, or anything that responds to matches can be a routing constraint. And you pass in the request, it passes in the request as an argument. And then that block returning true or false will say whether or not the routes that are in that constraints block are going to be matched. So you can actually do some interesting things with this. One pattern that I've sort of tried out a little bit is the idea of actually having, having active record models be constraints. And that sounds a little weird. But so if you look at the code here, you see, can everybody read the code okay? Just want to make sure it's big enough. Cool. So if you look here, you see that in my routes, I have constraints user do. And the idea here is that I want to constrain all of these routes to only apply to logged in users. So all I have to do to implement that is in my user model, I just define a class method called matches that looks at the request. And then, you know, I'm here, I'm saying, you know, if there's a user ID in the session, then that means the user is logged in. So we'll return true. And so that's just a really, I mean, to me, that's just a really readable way to say, you know, these are the routes that are going to happen when I have a user. You know, lots of applications will have something like sub domain based accounts. You can do the same sort of thing there. So let's have a constraints account. And here we're saying, we're going to actually do a little bit more, we're going to say, let's actually find an account from the sub domain on this request. And if there is one, then we know that there's an account and we can do all these routes. So, you know, why would you want to do this? I've found in Rails 3 that what I really like is to, you know, in previously in Rails 2, I wrote sub domain foo, which was sort of my attempt to do some of this sort of thing before the Rails 3 router was available. And what's frustrating is that you always sort of have to write some sort of catch all or some sort of hacky thing where it's like, you know, well, if there's not a user, then redirect them to this, you know, splash page or whatever. But in Rails 3, what's really handy is that if you use these routing constraints, you know, they just don't even see the routes that they're not supposed to see based on the application state, based on the current request. So I think that keeps everything really clean. You don't have to worry about, you know, oh, are my, you know, cut out there? Are my user account routes going to leak through to the person who's just going to the website to sign up for the first time? Now, if you want to take this too far, basically, you can create a little reverse constraint module, include that in a in something and that gives you a not class method that will then reverse the normal matches class method. So if you want to now say, give me routes only for when users are not logged in, then you would say constraints user dot not. This is probably taking it too far. It's just fun little thing. And I can I'm I'm saying this and I'm a little hesitant to say this because I could see people sort of jumping up and shouting that mixing passing the request into the model is a terrible practice that should never be done. I'd be willing to listen to that, but I kind of like how it looks. So I'm doing it if you want to argue against me, feel free to hit me up in the hall later. Another thing that Rails three lets you do is it lets you define regular expressions for parameters. And that is a lot more powerful than you might expect. Because that lets you do things that you didn't necessarily think you could do. So in this example, if you want to do GitHub style routing, where, you know, everything in your app is namespace based on this, you know, slash user slash repo at the start. That seems like it's going to be really tough to do, especially using just the standard Rails, you know, resources calls. But as you can see here, all I actually have to do is I say resources repos, and then I specify a regular expression for the ID of, you know, it's going to be some letters and numbers followed by some letters and numbers with a slash in between. So even something like slashes you can actually have in your routing parameters. And then the other thing that I found while I was looking through and trying to make this example is that if you can if you pass in path with a blank string, that's actually going to make it so that the root, you know, that's just going to go like straight to the root with no path prefix at all. So rather than being slash repos slash ID, instead it's just slash ID. So you still get to use all of the nice restful resources DSL that you like in Rails, but you can specify these powerful constraints. And this is just something that I think really can clean up how your Routes file looks. It can really clean up, you know, how you're dealing with these sorts of things. So I think that's kind of fun. So next up, let's talk about some of the things you can do with application config. Customizing generators. So one thing that bothered me for a long time, and this is one of those things where every time it would just cost me like 10 or 15 seconds, and it really annoyed me, but I didn't take the time to actually fix it for a long time. I don't like having a helper for every controller that I generate. That kind of annoys me, because I use, you know, I use helpers that are just grouped to whatever they're making a helper for, and that's not usually actually a controller, that's usually some other kind of behavior. So I don't really want Rails to be generating helpers every time I generate a controller. And as it turns out, that's just a one-liner that you can add to application.rv. So that was something that it took me a long time to look up, but once I did, that saved me 15 seconds every time that I created a controller, because I'm not then immediately removing the helper that it creates. You can also do things like I prefer to use the SAS syntax instead of SCSS. So with Rails 3.1, by default, when you generate a controller, it'll generate, you know, controller name dot CSS dot SCSS. But actually, if you prefer to use the SAS syntax, that's also just one-liner in your config application.rv. And so I guess sort of, you know, these are one-liners, they're not that hard to find. You know, if you Google for it, it's going to be a Stack Overflow post somewhere in the first page. But I guess the thing that I'm trying to get across is that you should try to find these things. You know, anytime that you have pain, anytime that you're annoyed with how your development is going, you should try to find something that makes that pain go away. So let's move on and talk about some of the things you can do with ActiveRecord. Migration shortcuts, most people probably know these. When you're creating a table with ActiveRecord migrations, rather than doing t dot integer, you know, user ID, you can instead do t dot belongs to user, and that will create the user ID field as an integer, but it will also create an index automatically for that. You can also do polymorphic that will automatically create, in this case, a commentable ID and a commentable type field and also index based on that. So, you know, that's just a handy thing that it makes your migration match your model a little better and it makes things just go a little faster. And that's what this is all about. Also, when you're generating a model or you're generating a migration, you can use shortcuts. So if you pass arguments after Rails G model comment, for example, here, you can pass the column name and then the type that you want it to be and you can even do those belongs to's and things like that that I just talked about. So when that generates the migration, that's going to automatically generate it with the t dot text body and then t dot belongs to user. And something that I actually don't understand how it works, but it does, is if you're generating just a migration and say you say Rails G migration adds spam to comments with the same column name, colon type argument, that will actually create the proper add column call on the correct table. And I'm assuming that does some sort of introspection on what you're calling the migration. I just wanted to point that out because if anyone knows how that works or why it works, I'm interested. So, mass assignment roles. This is something new in Rails 3.1 that I think is a great idea. So normally, you know, everyone's used to using adder protected or adder accessible to, you know, define what is mass accessible, you know, what can I set safely on this model. Rails 3.1 adds the concept of roles for that. So what you can do is if you say, you know, adder protected something, that's actually saying that this is protected for the default role. And in an update method, if I call user.update attributes, you know, params user, like you might do, that's not going to update the verified column. It's just going to ignore it in that call. But then let's say that you have some kind of admin controller and you're wanting to do the same thing. If you pass in a second argument that is an as and then you give it a role and that's an arbitrary symbol, then that's going to let you override that default scope and that's actually going to let you set verified. So that's something that I think that I've a number of times, you know, I'll create some admin controller and it'll be like rather than doing update attributes, you'll do like attributes equals and then you'll have to manually run through and set the fields that you want the admin to be able to override. So this is just a lot cleaner way to do it and I love that that's baked into Rails 3.1. Touching. So when you have associations, you can specify when you have belongs to associations you can specify touch true and what that does is anytime the model is saved it will automatically update the updated at key or the updated at column on the association. This is just a direct SQL call. It doesn't run any callbacks on the parent model or anything like that. But something that that's useful for is if you're using timestamp based caching in your application then that allows you to sort of bubble everything up from the lowest level all the way to the top level. So anytime you know let's say I have a post with a bunch of comments and those comments you know have replies I can have reply bubble up to comment bubble up to post and then bubble up to say a section of a blog and so all the way up that chain that updated at changes so that means that if you're using like a timestamp based cash key then that'll change all the way up when you go forward. So that's just a little thing that again adds convenience and can sort of automatically do something that might be in. We're going to talk now about some things you can do with action pack. This is another new feature for Rails 3.1 super fast HTTP basic. So the most common case that I can think of for this is you know I'm building an application I'm not ready to show it to the public so I just want to site-wide have an HTTP basic that has a password so that the developers can log in and see what's going on. So all you have to do now is HTTP basic authenticate with and specify a name and a password and here I'm assuming you're deploying something like HeroCoup where you can set that in the environment. So all you have to do is that and that automatically oops oh I just lost my place. Hooray for gestures. Aren't CSS transitions great? So again a useful thing new in Rails 3.1 that I'm going to be using hopefully you will do. HTML data tags also new in Rails 3.1 so anytime you use the content tag which actually bubbles up to a lot of things in Rails that'll bubble up to link to and all of your different tag helpers you can specify a data so this would be the same place that you're specifying like class or ID or other HTML attributes but you can specify data which is can actually be a hash and then that hash will automatically set the HTML5 data dash key attributes so you know for instance if I have if I want to be representing like one of my models then I can do a content tag and I can specify some keys that I want to include from the model and then just automatically have those all set on the data tag so that I can do something with them in JavaScript once the page loads. Excuse me. That's editable. Who knew? Actions is rack endpoints. This is something that I haven't found a lot of occasion other than writing omni-off. There's actually a case for this but Rails actions are now all rack endpoints and that lets you do something where you can just say controller name dot action and then pass in a symbol of the action name and that will actually be a rack endpoint that you can call that you can run in a you know rack up file that you can do anything you'd expect with a rack endpoint and that's a really powerful thing that you can do because before you know Rails sort of felt like this monolithic thing where you have to be running the entire application and there's no real modularity to it but now that you can do this for instance if you have a middleware and that middleware has options that you can pass on that are supposed to be rack endpoints you don't have to write a custom endpoint you can just say well I just want that to be my controller so you know if there's like an error middle if there's like an error that it's expecting to be able to have a pass have passed a rack middleware to or a rack endpoint to you can just say errors controller action show and that works how you'd expect it to capturing output in helpers so this changed in rails 3 it's something that I've experimented a lot with because I like sort of defining almost a view DSL while I'm building rails apps so that everything's done anything in a consistent way so if I have a consistent UI pattern that's repeated you know if it's something simple sometimes I won't like make a partial that then you pass a bunch of locals into instead I'll just make it a block block helper that lets you sort of declaratively say what kind of content you're building and it almost brings the semantics of your views to another level so here the example I'm just creating a shout helper and this is probably something you would never want to do but all it does is you know in my view if I say shout do and then I have you know whatever content there I can capture that content using this without buffer method call through and I'm just going to upcase everything and return it so that'll make everything that comes in this block upcase before it's rendered so that's a you know obviously a fictional example but there are real use cases where you want to do that one example is if you're creating something where you have a common UI like a tab set and you want to be able to say like you know tab set do and then inside that you want to say tab do tab do tab do and that builds a UI in a consistent way you can use this to capture that output to then be able to manipulate it modify it you know wrap things around it and generally control it better bonus tips so that goes through sort of all of the general rail stuff earlier I actually use an example of this active support concern so excuse me active support concern is basically a little helper for writing modules that lets you do the pattern that you that most people are used to in a more succinct way so what you what you know traditionally was the way you do it is you would define on your module a self that included that take that gets called when the modules included and passes in the class that's including it then you would say you know extend class methods include instance methods and then maybe you want to evaluate something on the class based on your inclusions that you just did so you know that's how it was and then starting in Rails 3 active support concern is sort of just a standard API for that where you just in your module you say extend active support concern it will automatically pick up a class methods or an instance methods module that are in that and it and include them the way you'd expect and you also get some callback hooks so you can just say included do and then this is running a class eval when the modules included so you can automatically have some callback actions and things like that a personal asset gem so this is something that I haven't actually taken the time to build for myself but I really want to because one of the biggest pain points that I another pain point that I have is every time I'm building an app and I just have a bunch of little JavaScript libraries that I reuse a bunch of times and then every single time I'm building an app you know I have to download them again and put them in the directory and all of that the asset pipeline gives us powerful ways to treat JavaScript as a first class citizen in Rails so between that and Rails engines you can actually just create sort of your own directory of like here's all the JavaScripts that I use on a regular basis and then you can just drop that gem into your application and use it so we're going to this is just you know basically how you can set up a gem really quickly if you have bundler installed you can just say bundle gem and then specify a name that'll generate sorry that'll generate a folder that has a live directory a gem spec all the stuff that you need for a gem then you'd want to add a dependency for Rails and in the lib file that it creates by default you would just define a Rails engine and anytime you define a Rails engine even if it's an empty class that tells Rails this gem is a Rails engine which means that I should look in the app directory in the vendor directory for things that I can include in the application so now you can just drop all of your favorite javascript into vendor slash assets slash javascripts and then just you know drop it in there drop modernizer in there if you're using slider.js drop that in there and then in any project all you have to do is add your new gem that you pushed up to github into the repository and then in your app assets in any of your app assets files you can just require them as if you had just dropped them into your project yourself you know so you do this one time you build this nice library of javascripts that you're going to use you know most of the time and then from there on you just pull the gem and you require it and you've got everything you need. Standard library timeouts so there are sometimes when you might be making a call to an external service sometimes you may not be able to control the timeout on that if you're using someone else's library they don't have that kind of support you can pretty much override that in ruby 192 by just using the built-in timeout library so you just require timeout and then you say you know timeout timeout in the number of seconds and then you call block so if this block takes any longer than five seconds to execute it's going to raise out a timer a timeout error and then from there you can just say well you know whatever external service you're trying to call is taking too long so we're just going to break out of that so that keeps you in control of your code even if you're using libraries that may not give you the ability to do that kind of timeout and the last thing and I actually added this while Ola was giving his talk because it reminded me of something that I do actually quite a bit but he was talking about how much how useful enumerators are and you know one of the fun little enumerators that active support gives you is you know do a number dot times and that'll give you an iterator that'll go through you know five times if you do five dot times and that's usually used with something like each where it's or yeah five dot times do and then that just iterates through but you can actually do some other interesting things with it so I recently needed to do something that was generating sort of fake paragraphs of text and I know that there are gems out there to do this but for various reasons I needed to have like my own word set and stuff like that so here we have a function method that just defines a random word so you would just have an array that's a bunch of words here and this is another little trick that's useful if you need a random element of an array you can just say sort by ran dot first I can't tell you if that's performant but it's it works and then to generate a random sentence and this is using another one of Ola's tricks where I'm executing some arbitrary Ruby in the default initializer to make it the length between five and thirteen words by default so you can actually say number dot times and then you can call any of the innumerable methods so in this case I can call map and then I can call random word and that's going to return an array that is the length of the of the you know number of times that it's being called filled with random words and so there from there I can just capitalize the first word join them together with spaces and add a period and I've generated a random sentence so that's all of the little tricks that I have and I I'll take questions but I'd also like to take comments in the forms of you know what are the little tricks that you have that you use that you think make your life easier that everyone might know might not know about so questions or awesome tricks that you can do I'm open yeah and this is why I'd give this at a ruby conference so that I can be corrected so thank you so if you're using j ruby this is a great practice and if you're using MRI yeah there you go so if you're using MRI you're not using threads and if you're using j ruby it's safe so you're you're good to go anybody else yeah is it hey what do you know sometimes you sometimes I forget what's an active support in ruby as an open source maintainer other people do a lot too um so yeah just plain ruby you can do that anywhere yeah dot sample is that new in 192 or is that always been around all right see I actually love giving these kinds of talks because then everyone tells me like how the things I'm doing it are wrong and then I improve so I learned from all of you more than you learned from me and that's great I think that's my time thank you very much and if you want to tell me more tricks find me in the halls because I'm very interested all right let's hear it from Michael by