How to create this MongoMapper custom data type?

Posted by Kapslok on Stack Overflow See other posts from Stack Overflow or by Kapslok
Published on 2010-03-21T06:29:33Z Indexed on 2010/03/21 6:41 UTC
Read the original article Hit count: 602

I'm trying to create a custom MongoMapper data type in RoR 2.3.5 called Translatable:

class Translatable < String
  def initialize(translation, culture="en") 
  end 

  def languages
  end

  def has_translation(culture)?
  end

  def self.to_mongo(value) 
  end 

  def self.from_mongo(value) 
  end 
end 

I want to be able to use it like this:

class Page 
  include MongoMapper::Document 
  key :title, Translatable, :required => true 
  key :content, String 
end

Then implement like this:

p = Page.new 
p.title = "Hello" 
p.title(:fr) = "Bonjour" 
p.title(:es) = "Hola" 
p.content = "Some content here" 
p.save

p = Page.first
p.languages
=> [:en, :fr, :es]
p.has_translation(:fr)
=> true
en = p.title 
=> "Hello" 
en = p.title(:en)
=> "Hello"
fr = p.title(:fr) 
=> "Bonjour" 
es = p.title(:es) 
=> "Hola" 

In mongoDB I imagine the information would be stored like:

{ "_id" : ObjectId("4b98cd7803bca46ca6000002"), "title" : { "en" : 
"Hello", "fr" : "Bonjour", "es" : "Hola" }, "content" : "Some content 
here" } 

So Page.title is a string that defaults to English (:en) when culture is not specified.

I would really appreciate any help.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about mongomapper