Skip to content

Instantly share code, notes, and snippets.

@jch
Created April 12, 2012 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jch/2370334 to your computer and use it in GitHub Desktop.
Save jch/2370334 to your computer and use it in GitHub Desktop.
module FromParam
extend ActiveSupport::Concern
module ClassMethods
def [](key)
find_by_slug(key) || find_by_id(key)
end
def from_param(param)
self[param]
end
def from_param!(param)
from_param(param) or raise MongoMapper::DocumentNotFound
end
end
end
MongoMapper::Document.plugin(FromParam)
class Post
include MongoMapper::Document
key :slug
many :comments
end
class Comment
include MongoMapper::Document
key :slug
belongs_to :post
end
post = Post.create(:slug => 'post')
com1 = Comment.create(:slug => 'comment1', :post => post)
com2 = Comment.create(:slug => 'comment1', :post => post)
# This raises an ArgumentError as expected b/c Comment does respond_to :from_param
Post.first.comments.from_param
# However, because from_param doesn't return a Plucky::Query, it continues up the
# method missing chain.
Post.first.comments.from_param('comment1')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment