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.
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
|