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

#_add_association(association) ⇒ Object



42
43
44
# File 'lib/mongo_doc/attributes.rb', line 42

def _add_association(association)
  self._associations += [association] unless _associations.include?(association)
end

#_add_key(key) ⇒ Object



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

def _add_key(key)
  self._keys += [key] unless _keys.include?(key)
end

#_attributesObject



46
47
48
# File 'lib/mongo_doc/attributes.rb', line 46

def _attributes
  _keys + _associations
end

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



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
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/mongo_doc/attributes.rb', line 50

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|
    _add_key(name)
    attr_writer name

    unless default.nil?
      define_method("_default_#{name}", default.kind_of?(Proc) ? default : proc { default.duplicable? ? default.dup : 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 == Boolean
      module_eval(<<-RUBY, __FILE__, __LINE__)
        alias #{name}? #{name}  # alias active? active
      RUBY
    end

    if type.try(:respond_to?, :cast_from_string)
      define_method "#{name}_with_type=" do |value|
        if value.kind_of?(String)
          value = type.cast_from_string(value)
        end
        self.send("#{name}_without_type=", value)
      end
      alias_method_chain "#{name}=", :type
    end
  end
end