Skip to content

Instantly share code, notes, and snippets.

@glucero
Created March 1, 2013 17:33
Show Gist options
  • Save glucero/5066297 to your computer and use it in GitHub Desktop.
Save glucero/5066297 to your computer and use it in GitHub Desktop.
rtd data models
#!/usr/bin/env ruby
module RTD
module Model
include Enumerable
def all
to_a
end
def each
models = class_variable_get(:@@__model_collection__)
attributes = class_variable_get(:@@__model_attributes__)
import = class_variable_get(:@@__import_data__)
(models.count + import.count).times do |i|
if block_given?
if i >= models.count
models << new
data = CSV.parse(import.shift)
attributes.zip(*data) do |attribute, value|
models[i].send "#{attribute}=", value
end
end
yield models[i]
end
end
rescue NameError
init!
retry
end
def count
class_variable_get(:@@__model_collection__).count + class_variable_get(:@@__import_data__).count
rescue NameError
init!
retry
end
def snake_case
self.name.tap do |name|
name.gsub! /RTD::/, ''
name.gsub! /([A-Z]+)([A-Z][a-z])/, '\1_\2'
name.gsub! /([a-z\d])([A-Z])/, '\1_\2'
name.downcase!
end
end
def init!
dir = File.expand_path(File.dirname(__FILE__))
import = File.read(File.join dir, "#{snake_case}s.txt").lines.to_a
attributes = CSV.parse(import.shift).flatten
attributes = attributes.map { |attribute| attribute[/^(#{snake_case}_)?(.+)$/, 2].to_sym }
class_variable_set :@@__model_attributes__, attributes
attributes.each do |attribute|
define_method(attribute) { instance_variable_get("@#{attribute}") }
define_method("#{attribute}=") do |value|
instance_variable_set("@#{attribute}", value.strip) if value
end
end
class_variable_set :@@__import_data__, import
class_variable_set :@@__model_collection__, Array.new
end
end
end
class Calendar
extend RTD::Model
end
class CalendarDate
extend RTD::Model
end
class Route
extend RTD::Model
end
class Stop
extend RTD::Model
end
class Trip
extend RTD::Model
end
class StopTime
extend RTD::Model
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment