Module: Mongoid::AttributeConvertors::ClassMethods

Defined in:
lib/mongoid_misc/attribute_convertors.rb

Instance Method Summary collapse

Instance Method Details

#available_as_string(name, converter_name) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mongoid_misc/attribute_convertors.rb', line 42

def available_as_string name, converter_name
  converter = CONVERTORS[converter_name]
  raise "unknown converter name :#{converter_name} for :#{name} field!" unless converter
  
  from_string, to_string = converter[:from_string], converter[:to_string]
  name_as_string = "#{name}_as_string".to_sym
  define_method name_as_string do
    cache[name_as_string] ||= to_string.call(send(name))
  end
  
  define_method "#{name_as_string}=" do |value|
    cache.delete name_as_string                        
    self.send "#{name}=", from_string.call(value)
  end
end

#available_as_yaml(name) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/mongoid_misc/attribute_convertors.rb', line 58

def available_as_yaml name
  raise "delimiter not specified for :#{name} field!" unless delimiter
  method = "#{name}_as_string"
  define_method method do
    self.send(name).join(delimiter)
  end
  define_method "#{method}=" do |value|            
    value = (value || "").split(delimiter.strip).collect{|s| s.strip}
    self.send "#{name}=", value
  end
end

#field(name, options = {}) ⇒ Object

supporf for :as_string option



33
34
35
36
37
38
39
40
# File 'lib/mongoid_misc/attribute_convertors.rb', line 33

def field name, options = {}                       
  if converter_name = options[:as_string]
    available_as_string name, converter_name
    attr_protected "#{name}_as_string".to_sym if options[:protected]            
  end
  
  super
end