Useless Ruby Tricks: DATA and __END__

So maybe not totally useless certainly fun. Normally, ruby scripts are finished when you reach the end of a file; however, this is not always the case. You can end your script sooner by using the __END__ keyword in your script. Once added, everything you type after that will not be parsed by ruby.

So what?

Well, you can use the global variable DATA to get the contents of what you wrote after the __END__ block. DATA is actually a File object to just that piece of text in your script.

Continue reading

Blocks and Helpers, a Lovely Combination

Blocks rock and I couldn’t agree more. The functional programming aspect of ruby has started to interest me more and more. Blocks are used all over the place, with respond_to, collect, returning and ActionView::Helpers::FormHelper#form_for.

Sometimes, a design requires a little extra markup, perhaps something to get that rounded corner to work or what-have you. Now let’s say this piece of code requires certain classes, a certain kind of structure, including a tile, and has to be used in many places, something like a sidebar piece. Instead of copying and pasting this structure over and over, you can use a helper to make you life easier, and if you combine it with a block, it will just feel even more painless.

Continue reading

I heart Ruby: Metaprogramming

So today I had an interesting problem. For whatever the reason, I wanted to have a class automagically be created. It was going to be a helper model, and I didn’t feel like having umteen classes that all did the same thing, just had different names for different tables. My solution: use the power of ruby and metaprogramming

def create_new_active_record_model(class_name)
  klass = Class.new(ActiveRecord::Base) do
    belongs_to :old, :class_name => class_name
    def some_method_you_want
      "something"
    end
  end
  Object.const_set "#{class_name}Target", klass
end

I know that some of this could have been encapsulated in a polymorphic association but this allows you to do something beyond just keeping everything in one table, like with polymorphic associations.

Continue reading

Looking towards Rails 1.2 with CRUD

A couple of months ago, I was shown the article that DHH(David Heinemeier Hannson) wrote after he gave his presentation at RailsConf 2006. I looked at it then and kind of shrugged it off, mainly because I really didn’t know what the presentation was really about.

Tonight I found video of that presentation and I got excited about CRUD(Create, Read, Update, Delete). It pointed out that I’ve been making some controllers a little bloated. I have coupled much functionality into one controller; when looking back, I clearly could have separated out some functionality.

Continue reading