Sha256: 33af529011a2ec751db6e281a9fca14c1af71de894634eb8d6c9456490376874

Contents?: true

Size: 1.89 KB

Versions: 14

Compression:

Stored size: 1.89 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 :fields

      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)
        attr_protected name if options[:accessible] == false
      end

      # Returns the default values for the fields on the document
      def defaults
        fields.inject({}) do |defs,(field_name,field)|
          next(defs) if field.default.nil?
          defs[field_name.to_s] = field.default
          defs
        end
      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)
        add_dirty_methods(name)
      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}?") do
          attr = read_attribute(name)
          (options[:type] == Boolean) ? attr == true : attr.present?
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
mongoid-2.0.0.beta.20 lib/mongoid/fields.rb
mongoid-2.0.0.beta.19 lib/mongoid/fields.rb
mongoid-2.0.0.beta.18 lib/mongoid/fields.rb
mongoid-2.0.0.beta.17 lib/mongoid/fields.rb
mongoid-2.0.0.beta.16 lib/mongoid/fields.rb
mongoid-2.0.0.beta.15 lib/mongoid/fields.rb
mongoid-2.0.0.beta.14 lib/mongoid/fields.rb
mongoid-2.0.0.beta.13 lib/mongoid/fields.rb
mongoid-2.0.0.beta.11 lib/mongoid/fields.rb
mongoid-2.0.0.beta.10 lib/mongoid/fields.rb
mongoid-2.0.0.beta.8 lib/mongoid/fields.rb
mongoid-2.0.0.beta.9 lib/mongoid/fields.rb
mongoid-2.0.0.beta.12 lib/mongoid/fields.rb
mongoid-locomotive-2.0.0.beta9 lib/mongoid/fields.rb