Sha256: 4c134260c99d97d96f5ad6dd52dbc019012432f0602395445a8939e446c2f92e

Contents?: true

Size: 973 Bytes

Versions: 1

Compression:

Stored size: 973 Bytes

Contents

class EmbeddedHash < Hash
  include Mongoid::Fields::Serializable
  include ActiveModel::Validations

  def initialize(other = {})
    super()

    if other
      other.each do |k,v|
        self[k] = v
      end
    end

    self.assign_id
  end

  def self.allocate
    obj = super
    obj.assign_id

    obj
  end

  def self.field(name, opts = {})
    define_method(name) do
      if fetch(name.to_s, nil).nil?
        self[name.to_s] = opts[:default].kind_of?(Proc) ? opts[:default].call : opts[:default]
      else
        self[name.to_s]
      end
    end

    define_method("#{name}=") do |v|
      self[name.to_s] = v
    end
  end

  def id
    self["_id"]
  end
  alias :_id :id

  def serialize(v)
    v
  end

  def deserialize(v)
    self.class.new(v)
  end

#   def method_missing(name, *args, &block)
#     @table.send(name, *args, &block)
#   end

  def assign_id
    if fetch("_id", nil).nil?
      self["_id"] = BSON::ObjectId.new.to_s
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid_ext-0.7.1 lib/mongoid_ext/types/embedded_hash.rb