Created
August 21, 2011 09:51
-
-
Save Chris927/1160405 to your computer and use it in GitHub Desktop.
Repository Ideas (DDD style) for Rails
This file contains hidden or 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
| module GenericRepo | |
| def self.included(base) | |
| base.class_eval do | |
| extend ClassMethods | |
| end | |
| end | |
| module ClassMethods | |
| attr_accessor :model | |
| def create(params) | |
| puts "here we would create something, params=#{params}" | |
| end | |
| def create2(params) | |
| puts "create2 in GenericRepo, params=#{params}" | |
| end | |
| end | |
| end | |
| class D # this is the model | |
| def self.create(params) | |
| puts "this is D.create" | |
| end | |
| def self.build(params) | |
| puts "this is D.build, params=#{params}" | |
| end | |
| module GenericRepo::ClassMethods | |
| # only do this for stuff that should be available on | |
| # GenericRepo on class level (for all models) | |
| end | |
| @repo = Class.new do | |
| include GenericRepo | |
| self.model = D | |
| def self.create3(params) | |
| puts "create3, added later" | |
| puts "calling build..." | |
| model.build(params) | |
| end | |
| class << self | |
| alias_method :generic_create, :create | |
| end | |
| def self.create(param) | |
| puts "this is overriding the default repo one, right?" | |
| puts "and now we are calling the original:" | |
| self.generic_create(param) | |
| end | |
| end | |
| def self.repo | |
| @repo | |
| end | |
| end | |
| class E | |
| @repo = Class.new do | |
| include GenericRepo | |
| self.model = E | |
| end | |
| def self.repo | |
| @repo | |
| end | |
| end | |
| D.create("a parameter") | |
| D.repo.create("another param") | |
| D.repo.create2("bla") | |
| D.repo.create3("bla2") | |
| E.repo.create("blu") | |
| begin | |
| E.repo.create3("should fail!") | |
| raise "oops, should have failed" | |
| rescue NoMethodError => e | |
| # expected | |
| end |
Author
No, I haven't used it in a real project yet: Currently I'm on Rails 3.1 with ActiveRecord, and it didn't feel right to use it: I don't see an advantage of the approach above to just having static methods on models for non-instance-related stuff. But bear in mind that my DDD experience is limited :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting idea! Have you used this in a real world project yet? Curious as I'm deciding on going down the DDD route myself. Thx.