Module: ARSerializedArray

Defined in:
lib/ar_serialized_array.rb

Constant Summary collapse

VERSION =
File.read( File.join(File.dirname(__FILE__),'..','VERSION') ).strip

Instance Method Summary collapse

Instance Method Details

#serialized_array(attr_name, options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ar_serialized_array.rb', line 6

def serialized_array(attr_name, options={})
  options[:on_set] ||= lambda{|x|x}

  # getter
  define_method attr_name do
    YAML.load(read_attribute(attr_name).to_s) || []
  end

  # setter
  define_method "#{attr_name}=" do |value|
    value = options[:on_set].call(value) || []
    raise "Expected an Array, got: #{value.inspect}" unless value.is_a? Array
    value = (value.empty? ? nil : value.to_yaml)
    write_attribute attr_name, value
  end

  # accessors e.g. xxx_as_text
  if options[:accessor]
    #getter
    define_method options[:accessor] do
      send(attr_name) * ", "
    end

    #setter
    define_method "#{options[:accessor]}=" do |value|
      send "#{attr_name}=", value.to_s.split(',').reject(&:blank?).map(&:strip)
    end
  end
end