Created
August 17, 2012 02:15
-
-
Save thorncp/3375343 to your computer and use it in GitHub Desktop.
Outrageous Ruby metaprogramming ಠ_ಠ. Also, quite fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "dependency_loader" | |
class BiosController < ApplicationController | |
extend DependencyLoader(:person) | |
def new | |
@bio = @person.bios.build | |
end | |
# ... | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def DependencyLoader(name) | |
Module.new do | |
include DependencyLoader | |
define_singleton_method :extended do |base| | |
base.__load_dependency__ name | |
end | |
end | |
end | |
module DependencyLoader | |
def __load_dependency__(name) | |
loader = "load_#{name}" | |
klass = name.to_s.classify.constantize | |
ivar = "@#{name}" | |
define_method loader do | |
if instance_variable_get(ivar).nil? | |
instance_variable_set ivar, klass.find(params["#{name}_id"]) | |
end | |
end | |
before_filter loader | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment