Module: MongoDoc::Attributes::ClassMethods

Defined in:
lib/mongo_doc/attributes.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object



32
33
34
35
36
# File 'lib/mongo_doc/attributes.rb', line 32

def self.extended(klass)
  klass.class_eval do
    singleton_class.alias_method_chain :attr_accessor, :mongo
  end
end

Instance Method Details

#_attributesObject



38
39
40
# File 'lib/mongo_doc/attributes.rb', line 38

def _attributes
  _keys + _associations
end

#attr_accessor_with_mongo(*args) ⇒ Object Also known as: key



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/mongo_doc/attributes.rb', line 42

def attr_accessor_with_mongo(*args)
  return attr_accessor_without_mongo(*args) if args.first == :validation_context
  opts = args.extract_options!
  default = opts.delete(:default)
  type = opts.delete(:type)
  args.each do |name|
    _keys << name unless _keys.include?(name)
    attr_writer name

    if default
      define_method("_default_#{name}", default.kind_of?(Proc) ? default : proc { default })
      private "_default_#{name}"

      module_eval(<<-RUBY, __FILE__, __LINE__)
        def #{name}                                # def birth_date
          unless defined? @#{name}                 #   unless defined? @birth_date
            @#{name} = _default_#{name}            #     @birth_date = _default_birth_date
          end                                      #   end
          class << self; attr_reader :#{name} end  #   class << self; attr_reader :birth_date end
          @#{name}                                 #   @birth_date
        end                                        # end
      RUBY
    else
      attr_reader name
    end

    if type and type.respond_to?(:cast_from_string)
      module_eval(<<-RUBY, __FILE__, __LINE__)
        def #{name}_with_type=(value)               # def birth_date_with_type=(value)
          if value.kind_of?(String)                 #   if value.kind_of?(String)
            value = #{type}.cast_from_string(value) #     value = Date.cast_from_string(value)
          end                                       #   end
          self.#{name}_without_type = value         #   self.birth_date_without_type = value
        end                                         # end
      RUBY
      alias_method_chain "#{name}=", :type
    end
  end
end