Module: Addresslogic::InstanceMethods

Defined in:
lib/addresslogic.rb

Instance Method Summary collapse

Instance Method Details

#address_parts(options = {}) ⇒ Object

Returns the parts of an address in an array. Example:

["Street1", "Street2", "City", "State Zip", "Country"]

This makes displaying addresses on your view pretty simple:

address.address_parts.join("<br />")

Options

  • only: fields you want included in the result

  • except: any fields you want excluded from the result



49
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
# File 'lib/addresslogic.rb', line 49

def address_parts(options = {})
  options[:only] = [options[:only]] if options[:only] && !options[:only].is_a?(Array)
  options[:except] = [options[:except]] if options[:except] && !options[:except].is_a?(Array)

  parts = []
  address_parts_fields.each do |part|
    if part.is_a?(Array)
      # We only want to allow 2d arrays
      subparts = []
      part.flatten.each do |subpart|
        next if !respond_to?(subpart)
        value = send(subpart)
        next if value.to_s.blank? || (options[:only] && !options[:only].include?(subpart)) || (options[:except] && options[:except].include?(subpart))
        subparts << value
      end
      parts << subparts unless subparts.compact.empty?
    else
      next if !respond_to?(part)
      value = send(part)
      next if value.to_s.strip == "" || (options[:only] && !options[:only].include?(part)) || (options[:except] && options[:except].include?(part))
      parts << value
    end
  end
  
  result = parts.collect do |part|
    if part.is_a?(Array)
      part.collect{|sub| sub.to_s.strip.blank? ? nil : sub}.join(" ")
    else
      part.to_s.strip.blank? ? nil : part
    end
  end
  
  return result.compact
end