module Mongoo::Embedded::DescribeDsl

Public Instance Methods

embeds_many(attrib_key, opts) click to toggle source
# File lib/mongoo/embedded/describe_dsl.rb, line 9
def embeds_many(attrib_key, opts)
  raise(ArgumentError, "missing opt :class") unless opts[:class]
  define_embeds_many_method(attrib_key, opts)
end
embeds_one(attrib_key, opts) click to toggle source
# File lib/mongoo/embedded/describe_dsl.rb, line 4
def embeds_one(attrib_key, opts)
  raise(ArgumentError, "missing opt :class") unless opts[:class]
  define_embeds_one_method(attrib_key, opts)
end

Protected Instance Methods

define_embeds_many_method(attrib_key, opts) click to toggle source
# File lib/mongoo/embedded/describe_dsl.rb, line 14
def define_embeds_many_method(attrib_key, opts)
  embed_type   = opts[:type]
  embed_type ||= :hash

  as = attrib_key
  attrib_key = "#{attrib_key}"

  attribute(attrib_key, :type => embed_type, :define_methods => false)

  blk = Proc.new {
    if val = instance_variable_get("@#{as}")
      val
    else
      case embed_type
      when :hash then
        instance_variable_set("@#{as}",
          embedded_hash_proxy(get_or_set(attrib_key,{}), eval(opts[:class])))
      when :array then
        instance_variable_set("@#{as}",
          embedded_array_proxy(get_or_set(attrib_key,[]), eval(opts[:class])))
      end
    end
  }
  @klass.send(:define_method, as, &blk)

  unless opts[:validate] == false
    blk = Proc.new {
      send(as).each do |k,v|
        unless v.valid?
          v.errors.each do |field, messages|
            errors.add "#{attrib_key}.#{k}.#{field}", messages
          end
        end
      end
    }
    @klass.send(:define_method, "validate_#{as}", &blk)
    @klass.validate "validate_#{as}"
  end
end
define_embeds_one_method(attrib_key, opts) click to toggle source
# File lib/mongoo/embedded/describe_dsl.rb, line 55
def define_embeds_one_method(attrib_key, opts)
  as = attrib_key
  attrib_key = "#{attrib_key}"

  attribute(attrib_key, :type => :hash, :define_methods => false)

  blk = Proc.new {
    if val = instance_variable_get("@#{as}")
      val
    else
      if hash = get(attrib_key)
        instance_variable_set("@#{as}",
          embedded_doc(hash, eval(opts[:class])))
      end
    end
  }
  @klass.send(:define_method, as, &blk)

  blk = Proc.new { |obj|
    set(attrib_key, (obj.nil? ? nil : obj.to_hash))
    send("#{as}")
  }
  @klass.send(:define_method, "#{as}=", &blk)

  unless opts[:validate] == false
    blk = Proc.new {
      if v = send(as)
        unless v.valid?
          v.errors.each do |field, messages|
            errors.add "#{attrib_key}.#{field}", messages
          end
        end
      end
    }
    @klass.send(:define_method, "validate_#{as}", &blk)
    @klass.validate "validate_#{as}"
  end
end