Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Created October 1, 2010 20:14
Show Gist options
  • Select an option

  • Save rstacruz/606781 to your computer and use it in GitHub Desktop.

Select an option

Save rstacruz/606781 to your computer and use it in GitHub Desktop.
# What it does
# ------------
# With any typical Ohm model...
class Post < Ohm::Model
attribute :title
attribute :body
end
# you can have it's sets & lists have extra methods!
module Post::Collection
def summaries
"%i posts: %s" % [ size, map(&:title).join(", ") ]
end
end
# Lets try it like so:
Post.create title: "Hello there", body: "Lorem ipsum"
Post.create title: "Hi fellas!", body: "Dolor sit amet"
Post.all #=> #<Set (Post): ["1", "2"]>
Post.all.summaries #=> "2 posts: Hello there, Hi fellas!"
# How it's done
# -------------
class Ohm::Model
class Collection
alias _initialize initialize
def initialize(key, model, db=nil)
_initialize(key, model, db)
extend @model::Collection if @model::Collection.is_a?(Module)
end
end
end
# Why? What problem does this address?
# ------------------------------------
# Consider this scenario: you have a model...
class Comment < Ohm::Model
attribute :author
index :approved
end
# That needs to be used by other models.
class Post < Ohm::Model
set :comments, Comment
include HasComments
end
class Document < Ohm::Model
set :comments, Comment
include HasComments
end
# Now you'll probably want some way to manipulate them in groups.
module HasComments
def comment_authors
comments.map(&:author).uniq
end
def approved_comments
comments.find(approved: true)
end
end
# So you may:
Post[1].approved_comments #=> #<Set (Comment): ["1", "2"]>
# ------------------------------------------------------------------
# Wouldn't it be easier to just do it this way?
module Comment::Collection
def authors
map(&:author).uniq
end
def approved
find(approved: true)
end
end
# I think this is much cleaner!
Post[1].comments.approved #=> #<Set (Comment): ["1", "2"]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment