- 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
“Where Am I?” – seems *very* useful when debugging meta-programming soup.
October 17, 2008 at 5:31 pm
Hey, for dynamically creating activerecord models, take a look at my acts_as_fu project: [github.com/nakajima/acts_as_fu](http://github.com/nakajima/acts_as_fu). It does pretty much the same thing you showed, just a bit more concisely.
October 27, 2008 at 2:11 am
@Pat — I just used [acts_as_fu](http://github.com/nakajima/acts_as_fu) on a new project and it is the new hotness! Thanks!
January 10, 2009 at 1:32 am