signature.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. include GoingPostal
  2. class Signature < ActiveRecord::Base
  3. include ApplicationHelper
  4. belongs_to :user
  5. belongs_to :petition
  6. has_many :affiliations
  7. before_validation :format_zipcode
  8. before_save :sanitize_input
  9. validates_presence_of :first_name, :last_name, :petition_id,
  10. message: "This can't be blank."
  11. validates_presence_of :country_code, if: :location_required?
  12. validates :email, email: true
  13. validates :zipcode, length: { maximum: 12 }
  14. validate :country_code, :arbitrary_opinion_of_country_string_validity
  15. accepts_nested_attributes_for :affiliations, reject_if: :all_blank
  16. scope :filter, ->(f) do
  17. if f.present?
  18. where("LOWER(email) LIKE ? " +
  19. "OR LOWER(first_name || ' ' || last_name) LIKE ?",
  20. "%#{f}%".downcase, "%#{f}%".downcase)
  21. else
  22. all
  23. end
  24. end
  25. include ActionView::Helpers::DateHelper
  26. def self.pretty_count
  27. ActiveSupport::NumberHelper::number_to_delimited(self.count, delimiter: ",")
  28. end
  29. def arbitrary_opinion_of_country_string_validity
  30. if country_code.present? and full_country_name.nil?
  31. errors.add(:country_code, "Country Code might come from a spam bot.")
  32. end
  33. end
  34. def name
  35. [first_name, last_name].join(" ")
  36. end
  37. def location
  38. if anonymous
  39. country_code
  40. else
  41. [city, state, country_code].select(&:present?).join(", ")
  42. end
  43. end
  44. def time_ago
  45. time_ago_in_words(created_at)
  46. end
  47. def to_csv_line
  48. [name, email, city, state_symbol, full_country_name]
  49. end
  50. def state_symbol
  51. us_states_hash[state]
  52. end
  53. def location_required?
  54. petition.present? && !petition.enable_affiliations
  55. end
  56. def full_country_name
  57. begin
  58. IsoCountryCodes.find(country_code).name
  59. rescue IsoCountryCodes::UnknownCodeError
  60. nil
  61. end
  62. end
  63. private
  64. def format_zipcode
  65. zipcode = GoingPostal.format_zipcode(zipcode, country_code) || zipcode
  66. end
  67. def sanitize_input
  68. self.first_name = Sanitize.clean(first_name)
  69. self.last_name = Sanitize.clean(last_name)
  70. self.street_address = Sanitize.clean(street_address)
  71. self.email = Sanitize.clean(email)
  72. self.city = Sanitize.clean(city)
  73. self.state = Sanitize.clean(state)
  74. self.country_code = Sanitize.clean(country_code)
  75. self.zipcode = Sanitize.clean(zipcode)
  76. end
  77. def validate_zipcode
  78. unless GoingPostal.valid_zipcode?(zipcode, country_code)
  79. errors.add(:zipcode, "Invalid zip/postal code for country")
  80. end
  81. end
  82. end