Module: AttrCsv::ClassMethods

Defined in:
lib/attr-csv.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *arguments, &block) ⇒ Object



80
81
82
83
84
85
86
# File 'lib/attr-csv.rb', line 80

def method_missing(method, *arguments, &block)
  if method.to_s =~ /^((en|de)code)_(.+)$/ && attr_csved?($3)
    send($1, $3, *arguments)
  else
    super
  end
end

Instance Method Details

#attr_csv(*attributes) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/attr-csv.rb', line 18

def attr_csv(*attributes)
  instance_methods_as_symbols = instance_methods.map { | mthd | mthd.to_sym }

  attributes.each do | attribute |
    # Construct the name to be used for the CSV version
    # of the attribute
    csv_attribute_name = [ attribute.to_s, CSV_ATTR_EXTENSION ].join.to_sym

    # Create the accessors for the csv attribute
    unless is_active_record_model?(self)
      attr_reader csv_attribute_name unless instance_methods_as_symbols.include?(csv_attribute_name)
      attr_writer csv_attribute_name unless instance_methods_as_symbols.include?("#{csv_attribute_name}=".to_sym)
    end

    # Now, define the array attribute reader
    define_method(attribute) do
      (instance_variable_get("@#{attribute}") || 
       instance_variable_set("@#{attribute}", 
                             decode(attribute, send(csv_attribute_name))))
    end

    # and the array attribute writer
    define_method("#{attribute}=") do | value |
      send("#{csv_attribute_name}=", encode(attribute, value))
      instance_variable_set("@#{attribute}", value)
    end

    define_method("#{attribute}?") do
      value = send(attribute)
      value.respond_to?(:empty?) ? !value.empty? : !!value
    end

    csved_attributes << attribute.to_sym

  end

end

#attr_csved?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/attr-csv.rb', line 62

def attr_csved?(attribute)
  csved_attributes.include?(attribute.to_sym)
end

#csved_attributesObject



66
67
68
# File 'lib/attr-csv.rb', line 66

def csved_attributes
  @csved_attributes ||= superclass.csved_attributes.dup
end

#decode(attribute, csv_value) ⇒ Object



70
71
72
73
# File 'lib/attr-csv.rb', line 70

def decode(attribute, csv_value)
  return [] if csv_value.nil? || csv_value.empty?
  CSV.parse(csv_value).first
end

#encode(attribute, array_value) ⇒ Object



75
76
77
78
# File 'lib/attr-csv.rb', line 75

def encode(attribute, array_value)
  return nil if array_value.nil? || array_value.empty?
  array_value.to_csv.chomp
end

#is_active_record_model?(clazz) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
59
60
# File 'lib/attr-csv.rb', line 56

def is_active_record_model?(clazz)
  return false if clazz.nil?
  return true if clazz.to_s == 'ActiveRecord::Base'
  is_active_record_model?(clazz.superclass)
end