fork me on github

Creating Custom Rails Console Methods

Tired of typing the same commands in console every time you
fire it up?

The straw that breaks my back is “Character.find_by_name(‘super_long_nameski’)”

Using method missing, I’m going to make typing super_long_nameski
return its character.

One way to do this is to add methods to your .irbrc or .railsrc file.

However, knowing that everyone in my project will use this code, I’ve
decided to go ahead and add it to the project.

All code in the directory /config/initializers is run when rails starts, so
make a new file there.

/config/initializers/object.rb

  class Object
    def method_missing(*args)
      method = args[0].to_s
      if @controller.class == ApplicationController && #ensures it is in console
      character = Character.find_by_name(method)
          character
        else
          super
        end
      end
    end
  end

Yes, we’re adding a method to all objects; however,
“@controller.class == ApplicationController” ensures it’s being called
on the console main object.

If method_missing finds a character, it returns it. If not or if the command
is called outside of console, it returns the super value (probably an error).

  >> super_long_nameski
  => #<Character id: 2000297, salted_password: "f3a7bc8b40bb0256178", 
  email: "super_long_email@example.com", name: 'super_long_nameski', ...>
  

Finally!

blog comments powered by Disqus
Brent Wooden