Skip to content

Instantly share code, notes, and snippets.

@wmw
Created March 12, 2011 00:59
Show Gist options
  • Save wmw/866883 to your computer and use it in GitHub Desktop.
Save wmw/866883 to your computer and use it in GitHub Desktop.
Oo, fancy.
module ExternalRelations
class Linkage
def initialize(relation, caller, opts)
opts = opts.clone
@key = (opts.delete(:id) || :id)
@caller = caller
@target = relation.to_s.singularize.camelize.constantize.scoped.where(:"#{@caller.class.to_s.downcase}_id" => @caller.send(@key))
end
def <<(new_link_target)
new_link_target.send(:"#{caller.class.downcase}_id=", @caller.send(@key))
new_link_target.save
end
def method_missing(name, *args, &blk)
@target.send(name, *args, &blk)
end
end
def self.extended(base)
class << base
define_method(:has_external_relation) do |relation, opts|
self.send(:define_method, relation) do
ExternalRelations::Linkage.new(relation, self, (opts || {}))
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment