Created
August 19, 2011 22:20
-
-
Save ryanbriones/1158182 to your computer and use it in GitHub Desktop.
Code for an object mapper using plain ruby objects. Goal: make it easier to focus on creating objects based on behavior and only care about persistence at the very end
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mysql = MysqlStore.new | |
person_mapper = mysql.generate_table_mapping("person") do | |
map :first_name | |
map :last_name | |
map :dob, :dob_to_s_db | |
end | |
a = Person.new | |
a.first_name = "Ryan" | |
a.last_name = "Briones" | |
a.dob_year = 1982 | |
a.dob_month = 8 | |
a.dob_date = 30 | |
person_mapper.store(a) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MysqlStore | |
def store(mapping, object) | |
puts "INSERT INTO #{mapping.table_name} (#{mapping.get_mapped_column_names.join(', ')}) VALUES (#{mapping.get_mapped_column_names.map { |a| mapping.get_value_on_for_column(object, a).inspect }.join(', ')})" | |
end | |
def generate_table_mapping(table, &block) | |
TableMapping.new(self, table, &block) | |
end | |
class TableMapping | |
def initialize(store, table, &block) | |
@store = store | |
@table = table | |
instance_eval(&block) | |
end | |
def table_name | |
@table | |
end | |
def map(db_column, data_source = nil) | |
@map ||= {} | |
@map[db_column.to_s] = (data_source || db_column.to_s) | |
end | |
def get_mapping(db_column) | |
@map ||= {} | |
@map[db_column.to_s] | |
end | |
def get_mapped_column_names | |
@map.keys | |
end | |
def get_value_on_for_column(object, attribute) | |
object.send(get_mapping(attribute)) if get_mapping(attribute) | |
end | |
def store(object) | |
@store.store(self, object) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person | |
attr_accessor :first_name, :last_name, :dob_month, :dob_date, :dob_year | |
def dob | |
Date.civil(dob_year, dob_month, dob_date) | |
end | |
def dob_to_s_db | |
Time.mktime(dob_year, dob_month, dob_date).strftime("%Y-%m-%d") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment