Cool Rails Trick #638
This one is more for the developers. When we developers write code we try very hard to follow a DRY philosophy. DRY means don’t repeat your self, and when applied to code, it is the principal that there should be one singular place for all of the similar functionality to come from. A simple example would be sending an email. Let say your sites sends 6 different emails. In DRY code you would have one class (or method) to send all 6 emails, and you would pass in parameters to state the differences in each email.
Good developers do this with out much consideration or thought, and we refactor our code constantly to move the more complex examples to a DRYer state. One place that is aways been a problem historically is in the markup. HTML by default is repetitive and not very DRY. But there is a way to move it to a more dry state.
Lets Look at an example:
One of the most common things a client asks for is rounded corners. And regardless of the technique you use, it means repeating markup A LOT. For this example I am going to use a technique that I personally use on some sites. The entire problem is that we do not want to have to place 7 divs every time we want to make a rounded corner box. This is where a ruby/rails trick comes into play.
First up make two application level helpers (so that all views can access them)
This method renders a block to a partial, nothing too fancy. the options hash can be used just as if you were calling any other partial.
This is the method that gets called from a view.
Nothing to fancy here. notice the <%= body %> and <%= title %>. body is the block, title is in the options hash (check the helpers).
Nothing complicated here. But as you can see any elements or other blocks can be nested inside this. And it’s not just limited to rounded corners. Think about any place you might want to use a partial but theres just too much to pass into it, this will work there.
Coteyr.net Programming LLC. is about one thing. Getting your project done the way you like it. Using Agile development and management techniques, we are able to get even the most complex projects done in a short time frame and on a modest budget.
Feel free to contact me via any of the methods below. My normal hours are 10am to 10pm Eastern Standard Time. In case of emergency I am available 24/7.
Phone: (813) 421-4338