Sha256: d179800e8426785eec2a479e6e63686eaa5b067608daf134d945dca09dc33170

Contents?: true

Size: 1.72 KB

Versions: 1

Compression:

Stored size: 1.72 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc
  module Fields #:nodoc
    extend ActiveSupport::Concern
    included do
      # Set up the class attributes that must be available to all subclasses.
      # These include defaults, fields
      class_inheritable_accessor :defaults, :fields

      self.defaults = {}
      self.fields = {}

      delegate :defaults, :fields, :to => "self.class"
    end

    module ClassMethods #:nodoc
      # Defines all the fields that are accessable on the Document
      # For each field that is defined, a getter and setter will be
      # added as an instance method to the Document.
      #
      # Options:
      #
      # name: The name of the field, as a +Symbol+.
      # options: A +Hash+ of options to supply to the +Field+.
      #
      # Example:
      #
      # <tt>field :score, :default => 0</tt>
      def field(name, options = {})
        access = name.to_s
        set_field(access, options)
        set_default(access, options)
      end

      protected
      # Define a field attribute for the +Document+.
      def set_field(name, options = {})
        meth = options.delete(:as) || name
        fields[name] = Field.new(name, options)
        create_accessors(name, meth, options)
      end

      # Create the field accessors.
      def create_accessors(name, meth, options = {})
        define_method(meth) { read_attribute(name) }
        define_method("#{meth}=") { |value| write_attribute(name, value) }
        define_method("#{meth}?") { read_attribute(name) == true } if options[:type] == Boolean
      end

      # Set up a default value for a field.
      def set_default(name, options = {})
        value = options[:default]
        defaults[name] = value if value
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-pre-2.0.0.pre lib/mongoid/fields.rb