module AttrCsv::ClassMethods
Public Instance Methods
attr_csv(*attributes)
click to toggle source
# 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)
click to toggle source
# File lib/attr-csv.rb, line 62 def attr_csved?(attribute) csved_attributes.include?(attribute.to_sym) end
csved_attributes()
click to toggle source
# File lib/attr-csv.rb, line 66 def csved_attributes @csved_attributes ||= superclass.csved_attributes.dup end
decode(attribute, csv_value)
click to toggle source
# 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)
click to toggle source
# 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)
click to toggle source
# 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
method_missing(method, *arguments, &block)
click to toggle source
Calls superclass method
# 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