Commit 1a365aa

mo khan <mo@mokhan.ca>
2013-05-23 02:50:41
declare a better api for mapping table configuration"
1 parent cdabd05
Changed files (3)
lib
spec
integration
lib/humble/database_mapping.rb
@@ -0,0 +1,62 @@
+module Humble
+  class DefaultDataRowMapper
+    def initialize(configuration)
+      @configuration = configuration
+    end
+
+    def map_from(row)
+      @configuration[:type].new(row)
+    end
+  end
+
+  class MappingConfiguration
+    def initialize(attributes = {})
+      @attributes = {}
+      @attributes[:mapper] = DefaultDataRowMapper.new(self)
+    end
+
+    def table(name)
+      @attributes[:table] = name
+    end
+
+    def type(name)
+      @attributes[:type] = name
+    end
+
+    def primary_key(name)
+      @attributes[:primary_key] = name
+    end
+
+    def column(name)
+      @attributes[:column] = name
+    end
+
+    def [](key)
+      @attributes[key]
+    end
+  end
+
+  class DatabaseMapping
+    def initialize
+      @configuration = MappingConfiguration.new
+      run(@configuration)
+    end
+
+    def is_for?(item)
+      item == configuration[:type] || item.is_a?(configuration[:type])
+    end
+
+    def save_using(connection, item)
+      connection[configuration[:table]].insert(:name => item.name)
+    end
+
+    def find_all_using(connection, clazz)
+      Results.new(connection[configuration[:table]], configuration[:mapper])
+    end
+
+    private
+
+    attr_reader :configuration
+
+  end
+end
lib/humble.rb
@@ -2,6 +2,7 @@ require "humble/version"
 require "humble/session_factory"
 require "humble/session"
 require "humble/configuration"
+require "humble/database_mapping"
 
 module Humble
 
spec/integration/fixtures/movie_mapping.rb
@@ -6,27 +6,12 @@ class Movie
   end
 end
 
-class MovieMapping
-  def is_for?(item)
-    item == Movie || item.is_a?(Movie)
-  end
-
-  def save_using(connection, item)
-    connection[:movies].insert(:name => item.name)
-  end
-
-  def find_all_using(connection, clazz)
-    Results.new(connection[:movies], MovieMapper.new)
-  end
-
+class MovieMapping < Humble::DatabaseMapping
   def run(map)
     map.table :movies
-  end
-end
-
-class MovieMapper
-  def map_from(row)
-    Movie.new(row)
+    map.type Movie
+    map.primary_key :id
+    map.column :name
   end
 end