Skip to content

Instantly share code, notes, and snippets.

@kjs3
Created April 17, 2012 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjs3/2407911 to your computer and use it in GitHub Desktop.
Save kjs3/2407911 to your computer and use it in GitHub Desktop.
Event Model from a Rails project
require "iconv"
class Event < ActiveRecord::Base
belongs_to :event_category
has_many :line_items
has_many :region_links, :as => :region_linkable
has_many :regions, :through => :region_links
has_many :interest_links, :as => :interest_linkable
has_many :interests, :through => :interest_links
mount_uploader :attachment, AttachmentUploader
before_save :create_title_url, :geolocation
before_destroy :ensure_not_referenced_by_any_line_items
validates :title, :datetime_start, :datetime_end, :event_category_id, :presence => true
acts_as_taggable_on :tags
scope :past_events, where("datetime_end < ?", Date.today)
def date
if self.datetime_start.day == self.datetime_end.day
self.datetime_start.strftime('%A, %b %d, %Y')
else
"#{self.datetime_start.strftime('%A, %b %d')} - #{self.datetime_end.strftime('%A, %b %d, %Y')}"
end
end
def lat_lng
"#{self.lat}, #{self.lng}"
end
def time?
if self.datetime_start.hour == 0 && self.datetime_end.hour == 0
return false
else
return true
end
end
# ensure that there are no line items referencing this event
def ensure_not_referenced_by_any_line_items
if line_items.empty?
return true
else
errors.add(:base, 'Line Items present')
return false
end
end
def create_title_url
self.title_url = Iconv.conv("ASCII//TRANSLIT//IGNORE","UTF8", self.title).gsub(/\s+/,"_").gsub(/\W/,"").gsub(/(_)+/,"_").downcase
end
def geolocation
if self.address?
geo = Geokit::Geocoders::GoogleGeocoder.geocode(self.address)
self.lat = geo.lat
self.lng = geo.lng
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment