• Where am I? -- Ever need to find the name of the method you are currently within? Here's a this_method method! The magic is in the REGEX, of course.
module Kernel
  private
  def this_method
    caller[0] =~ /`([^']*)'/ and $1
  end
end
  • One project wanted to test a very ActiveRecord-specific Module in an isolated, generic way. After spending time researching techniques of mocking and stubbing the many, many ActiveRecord methods that would be touched, they decided to just dynamically create an ActiveRecord and a DB Table for it on the fly! They even used single table inheritance (STI)
  describe "MyMagicModule Mixin" do
    before(:all) do
      ActiveRecord::Base.connection.create_table "some_base_models",
                                                   :force => true do |t|
        t.string   "name"
        t.string   "type"
        t.integer  "some_model_b_id", :limit => 11
      end
    end

    after(:all) do
      ActiveRecord::Base.connection.drop_table "some_base_models"
    end


    class SomeBaseModel < ActiveRecord::Base;end

    class SomeModelA < SomeBaseModel
      include MyMagicModule

      belongs_to: :some_model_b
    end

    class SomeModelB < SomeBaseModel
      include MyMagicModule
    end

    it 'should use special belongs_to stuff from MyMagicModule' do
       model_a = SomeModelA.create!(
                        :name=> "Model A",
                        :some_model_be => SomeModelB.create!(:name => "Model B"))
       # test the functionality from MyMagicModule
    end
  end

Comments

  1. J. Ryan Sobol J. Ryan Sobol on October 17, 2008 at 05:31PM

    "Where Am I?" - seems very useful when debugging meta-programming soup.

  2. Pat Nakajima Pat Nakajima on October 27, 2008 at 02:11AM

    Hey, for dynamically creating activerecord models, take a look at my acts_as_fu project: github.com/nakajima/acts_as_fu. It does pretty much the same thing you showed, just a bit more concisely.

  3. Joe Moore Joe Moore on January 10, 2009 at 01:32AM

    @Pat -- I just used acts_as_fu on a new project and it is the new hotness! Thanks!