load_model 0.2.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,4 @@
1
+ ## v0.1
2
+
3
+ * Turned load_model from a plugin into a gem
4
+ * Moved all rails test support code into a rails sub-dir
@@ -0,0 +1,24 @@
1
+ MIT License
2
+ --------------------------------------------------------------------------------
3
+ Copyright (c) 2007 Thumble Monks, Justin Knowlden
4
+
5
+ Permission is hereby granted, free of charge, to any person
6
+ obtaining a copy of this software and associated documentation
7
+ files (the "Software"), to deal in the Software without
8
+ restriction, including without limitation the rights to use,
9
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the
11
+ Software is furnished to do so, subject to the following
12
+ conditions:
13
+
14
+ The above copyright notice and this permission notice shall be
15
+ included in all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24
+ OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,114 @@
1
+ # Load Model
2
+
3
+ A glorified before_filter that loads an instance of an `ActiveRecord` object as the result of searching for said object against a model defined by a given model name. The value of the HTTP request parameter `:id` will be used as the default lookup value. `LoadModel` will give you the ability to require an instance be found and/or override several other default behaviors.
4
+
5
+ class SillyFellowController < Application
6
+ load_model :silly_fellow
7
+ def action
8
+ @silly_fellow.do_something
9
+ end
10
+ end
11
+
12
+ You can require that a model instance be found for all actions or given actions. Default behavior is to not require that a model instance be found. When require is on and a record is not found, a `ThumbleMonks::RequiredRecordNotFound` Exception is thrown; which extends from ActiveRecord::RecordNotFound, for your convenience.
13
+
14
+ To turn require on for all actions, simply pass *true* to a provided `:require` attribute, like so:
15
+
16
+ load_model :silly_fellow, :require => true
17
+
18
+ To turn require on for specific actions, pass an array of action names to `:require`. The model will be loaded for all actions, regardless of whether or not required is provided, but the exception will only be raised when an record is not found for the provided actions.
19
+
20
+ load_model :silly_fellow, :require => [:show, :update]
21
+
22
+ To use a different parameter key and model than the default, you can provide the values in the `:paramater_key` and `:class` options (though not necessary to provide them together), like the following:
23
+
24
+ load_model :foo, :class => :user, :parameter_key => :bar_id
25
+
26
+ In the above example, `load_model` will assume the parameter_key and the model's primary/foreign key are both the same. For instance, the above example would result in a call like the following:
27
+
28
+ @foo = User.find_by_bar_id(params[:bar_id])
29
+
30
+ If you want to use a different lookup/foreign key than the default, you can also provide that key name using the `:foreign_key` parameter; like so:
31
+
32
+ load_model :foo, :class => :user, :parameter_key => :bar_id,
33
+ :foreign_key => :baz_id
34
+
35
+ Which would result in a call similar to the following:
36
+
37
+ @foo = User.find_by_baz_id(params[:bar_id])
38
+
39
+ If you want to only use `load_model` for some actions, you can still name them as you would with a `before_filter` using `:only` or `:except`. If you provide an `:only` and an `:except` value. `:only` will always win out over `:except` when there are collisions (i.e. you provide both in the same call)
40
+
41
+ load_model :foo, :only => [:show]
42
+ load_model :bar, :except => [:create]
43
+
44
+ ### Through
45
+
46
+ Load Model supports a :through option. With :through, you can load a model via the association of an existing loaded model. This is especially useful for RESTful controllers.
47
+
48
+ load_model :user, :require => true, :parameter_key => :user_id
49
+ load_model :post, :through => :user
50
+
51
+ In this example, a @post record will be loaded through the @user record with essentially the following code:
52
+
53
+ @user.posts.find_by_id(params[:id])
54
+
55
+ All of the previously mentioned options still apply (:parameter_key, :foreign_key, :require, :only, and :except) except for the :class option. Meaning you could really mess around!
56
+
57
+ load_model :user, :require => true, :parameter_key => :user_id
58
+ load_model :post, :through => :person, :parameter_key => :foo_id,
59
+ :foreign_key => :baz_id
60
+
61
+ Would result in a call similar to the following:
62
+
63
+ @person.posts.find_by_baz_id(params[:foo_id])
64
+
65
+ Require works as you would expect.
66
+
67
+ If you would like load_model to not assume a pluralized association name, you can provide the association name with the :association option. Like so:
68
+
69
+ class Person < ActiveRecord::Base
70
+ has_many :blog_postings
71
+ end
72
+
73
+ class PostController < ActionController::Base
74
+ load_model :post, :through => :person, :assocation => :blog_postings
75
+ end
76
+
77
+ ### From
78
+
79
+ Perhaps you don't need to do a subquery on a model's association and you just need to load a model from another's `belongs_to` or `has_one` association. This would be impossible in the above example. Instead, will want to use the :from option. Like so:
80
+
81
+ class Post < ActiveRecord::Base
82
+ belongs_to :user
83
+ end
84
+
85
+ class PostController < ActionController::Base
86
+ load_model :post
87
+ load_model :user, :from => :post
88
+ end
89
+
90
+ The example is contrived, but you get the point. Essentially, this would do the same as writing the following code:
91
+
92
+ @post = Post.find_by_id(params[:id])
93
+ @user = @post.user
94
+
95
+ ## Installation
96
+
97
+ sudo gem install thumblemonks-load_model
98
+
99
+ ## Requirements
100
+
101
+ 1. Ruby 1.8.6 or higher
102
+ 2. Rails 2.x or higher
103
+
104
+ ## Acknowledgements
105
+
106
+ Anyone who developed, discussed, or any other way participated in HTTP, REST, and Rails.
107
+
108
+ ## Contact
109
+
110
+ Justin Knowlden <gus@gusg.us>
111
+
112
+ ## License
113
+
114
+ See MIT-LICENSE
@@ -0,0 +1,22 @@
1
+ require 'rake'
2
+ require 'rake/testtask'
3
+ require 'rake/rdoctask'
4
+
5
+ desc 'Default: run unit tests.'
6
+ task :default => :test
7
+
8
+ desc 'Test the load_model plugin.'
9
+ Rake::TestTask.new(:test) do |t|
10
+ t.libs << 'lib'
11
+ t.pattern = 'test/**/*_test.rb'
12
+ t.verbose = true
13
+ end
14
+
15
+ desc 'Generate documentation for the load_model plugin.'
16
+ Rake::RDocTask.new(:rdoc) do |rdoc|
17
+ rdoc.rdoc_dir = 'rdoc'
18
+ rdoc.title = 'LoadModel'
19
+ rdoc.options << '--line-numbers' << '--inline-source'
20
+ rdoc.rdoc_files.include('README')
21
+ rdoc.rdoc_files.include('lib/**/*.rb')
22
+ end
@@ -0,0 +1,176 @@
1
+ require 'thumblemonks/model_loader'
2
+
3
+ module ThumbleMonks #:nodoc:
4
+ module LoadModel
5
+
6
+ class RequiredRecordNotFound < ActiveRecord::RecordNotFound; end
7
+
8
+ def self.included(klass)
9
+ klass.extend(ClassMethods)
10
+ end
11
+
12
+ module ClassMethods #:nodoc
13
+ # A glorified before_filter that loads an instance of an ActiveRecord
14
+ # object as the result of searching for said object against a model
15
+ # defined by a given model name. The value of the HTTP request parameter
16
+ # :id will be used as the default lookup value. LoadModel will give you
17
+ # the ability to require an instance be found and/or override several
18
+ # other default behaviors.
19
+ #
20
+ # Example
21
+ # class SillyFellowController < Application
22
+ # load_model :silly_fellow
23
+ # def action
24
+ # @silly_fellow.do_something
25
+ # end
26
+ # ens
27
+ #
28
+ # You can require that a model instance be found for all actions or given
29
+ # actions. Default behavior is to not require that a model instance be
30
+ # found. When require is on and a record is not found, a
31
+ # ThumbleMonks::RequiredRecordNotFound Exception is thrown; which does
32
+ # conveniently extend ActiveRecord::RecordNotFound.
33
+ #
34
+ # To turn require on for all actions, simply pass _true_ to a provided
35
+ # <em>:require</em> attribute, like so:
36
+ #
37
+ # Example
38
+ # load_model :silly_fellow, :require => true
39
+ #
40
+ # To turn require on for specific actions, pass an array of action names
41
+ # to <em>:require</em>. The model will be loaded for all actions,
42
+ # regardless of whether or not required is provided, but the exception
43
+ # will only be raised when an record is not found for the provided
44
+ # actions.
45
+ #
46
+ # Example
47
+ # load_model :silly_fellow, :require => [:show, :update]
48
+ #
49
+ # To use a different parameter key and model than the default, you can
50
+ # provide the values in the :paramater_key and :class options (though not
51
+ # necessary to provide them together), like the following:
52
+ #
53
+ # Example
54
+ # load_model :foo, :class => :user, :parameter_key => :bar_id
55
+ #
56
+ # In the above example, _load_model_ will assume the parameter_key is
57
+ # :bar_id while assuming the model's primary/foreign is still :id. For
58
+ # instance, the above example would result in a call like the following:
59
+ #
60
+ # @foo = User.find_by_id(params[:bar_id])
61
+ #
62
+ # If you want to use a different lookup/foreign key than the default, you
63
+ # can also provide that key name using the :foreign_key parameter; like
64
+ # so:
65
+ #
66
+ # Example
67
+ # load_model :foo, :class => :user, :parameter_key => :bar_id,
68
+ # :foreign_key => :baz_id
69
+ #
70
+ # Which would result in a call similar to the following:
71
+ #
72
+ # @foo = User.find_by_baz_id(params[:bar_id])
73
+ #
74
+ # If you want to only use load_model for some actions, you can still name
75
+ # them as you would with a before_filter using :only or :except. If you
76
+ # provide an :only and an :except value. :except will always win out over
77
+ # :only in the event of a collision.
78
+ #
79
+ # Example
80
+ # load_model :foo, :only => [:show]
81
+ # load_model :bar, :except => [:create]
82
+ #
83
+ # == Through
84
+ #
85
+ # Load Model supports a :through option. With :through, you can
86
+ # load a model via the association of an existing loaded model. This is
87
+ # especially useful for RESTful controllers.
88
+ #
89
+ # Example
90
+ # load_model :user, :require => true, :parameter_key => :user_id
91
+ # load_model :post, :through => :user
92
+ #
93
+ # In this example, a @post record will be loaded through the @user record
94
+ # with essentially the following code:
95
+ #
96
+ # @user.posts.find_by_id(params[:id])
97
+ #
98
+ # All of the previously mentioned options still apply (:parameter_key,
99
+ # :foreign_key, :require, :only, and :except) except for the :class
100
+ # option. Meaning you could really mess around!
101
+ #
102
+ # Example
103
+ # load_model :user, :require => true, :parameter_key => :user_id
104
+ # load_model :post, :through => :person, :parameter_key => :foo_id,
105
+ # :foreign_key => :baz_id
106
+ #
107
+ # Would result in a call similar to the following:
108
+ #
109
+ # @person.posts.find_by_baz_id(params[:foo_id])
110
+ #
111
+ # Require works as you would expect.
112
+ #
113
+ # If you would like load_model to not assume a pluralized association
114
+ # name, you can provide the association name with the :association
115
+ # option. Like so:
116
+ #
117
+ # Example
118
+ # class Person < ActiveRecord::Base
119
+ # has_many :blog_postings
120
+ # end
121
+ # class PostController < ActionController::Base
122
+ # load_model :post, :through => :person, :assocation => :blog_postings
123
+ # end
124
+ #
125
+ # == From
126
+ #
127
+ # Perhaps you don't need to do a subquery on a model's association and
128
+ # you just need to load a model from another's belongs_to or has_one
129
+ # association. This would be impossible in the above example. Instead,
130
+ # will want to use the :from option. Like so:
131
+ #
132
+ # Example
133
+ # class Post < ActiveRecord::Base
134
+ # belongs_to :user
135
+ # end
136
+ # class PostController < ActionController::Base
137
+ # load_model :post
138
+ # load_model :user, :from => :post
139
+ # end
140
+ #
141
+ # The example is contrived, but you get the point. Essentially, this
142
+ # would do the same as writing the following code:
143
+ #
144
+ # Example
145
+ # @post = Post.find_by_id(params[:id])
146
+ # @user = @post.user
147
+ def load_model(name, opts={})
148
+ unless loaders
149
+ self.class_eval { before_filter :load_specified_models }
150
+ write_inheritable_attribute(:loaders, [])
151
+ end
152
+ loaders << loader_class(opts).new(name, opts)
153
+ end
154
+
155
+ def loaders; self.read_inheritable_attribute(:loaders); end
156
+ private
157
+ def loader_class(opts)
158
+ return ThumbleMonks::ThroughModelLoader if opts[:through]
159
+ return ThumbleMonks::FromModelLoader if opts[:from]
160
+ ThumbleMonks::AssociativeModelLoader
161
+ end
162
+ end # ClassMethods
163
+ private
164
+ def load_specified_models
165
+ self.class.loaders.each do |loader|
166
+ if loader.action_allowed?(action_name)
167
+ obj = loader.load_model(self)
168
+ raise RequiredRecordNotFound if obj.nil? && loader.action_required?(action_name)
169
+ instance_variable_set(loader.assigns_to, obj)
170
+ end
171
+ end
172
+ end # load_specified_models
173
+ end # LoadModel
174
+ end # ThumbleMonks
175
+
176
+ ActionController::Base.send(:include, ThumbleMonks::LoadModel)
@@ -0,0 +1,90 @@
1
+ module ThumbleMonks #:nodoc:
2
+ class NoModelLoaderFound < Exception; end
3
+
4
+ class ModelLoader #:nodoc
5
+ attr_reader :assigns_to, :except, :only, :requires
6
+
7
+ def initialize(name, opts={})
8
+ config = {:require => false}.merge(opts)
9
+ @assigns_to = "@#{name}".to_sym
10
+ @requires = parse_required_actions(config[:require])
11
+ @except = stringify_array(config[:except])
12
+ @only = stringify_array(config[:only])
13
+ end
14
+
15
+ def action_allowed?(action)
16
+ return false if except.include?(action)
17
+ only.empty? ? true : only.include?(action)
18
+ end
19
+
20
+ def action_required?(action)
21
+ requires == true || requires.include?(action)
22
+ end
23
+
24
+ def load_model(controller)
25
+ raise NoModelLoaderFound
26
+ end
27
+ private
28
+ def parse_required_actions(actions)
29
+ actions == true ? true : stringify_array(actions)
30
+ end
31
+
32
+ def parameter_value(controller) controller.params[parameter_key]; end
33
+
34
+ def stringify_array(value) Array(value).map(&:to_s); end
35
+
36
+ def retrieve_association_through(controller, instance_variable_name)
37
+ controller.instance_variable_get(instance_variable_name).send(@association)
38
+ end
39
+ end # ModelLoader
40
+
41
+ class AssociativeModelLoader < ModelLoader #:nodoc
42
+ attr_reader :load_through, :parameter_key, :foreign_key
43
+
44
+ def initialize(name, opts={})
45
+ super
46
+ config = {:parameter_key => :id, :foreign_key => :id, :class => name}.merge(opts)
47
+ @load_through = config[:class].to_s.classify.constantize
48
+ @parameter_key = config[:parameter_key].to_s
49
+ @foreign_key = config[:foreign_key].to_s
50
+ end
51
+
52
+ def load_model(controller)
53
+ begin
54
+ lookup = parameter_value(controller)
55
+ source(controller).send("find_by_#{foreign_key}", lookup) unless lookup.blank?
56
+ rescue ActiveRecord::StatementInvalid
57
+ nil
58
+ end
59
+ end
60
+ private
61
+ def source(controller)
62
+ load_through
63
+ end
64
+ end # AssociativeModelLoader
65
+
66
+ class ThroughModelLoader < AssociativeModelLoader #:nodoc
67
+ def initialize(name, opts={})
68
+ super
69
+ @load_through = "@#{opts[:through]}".to_sym
70
+ @association = opts[:association] || name.to_s.pluralize
71
+ end
72
+ private
73
+ def source(controller)
74
+ retrieve_association_through(controller, load_through)
75
+ end
76
+ end # ThroughModelLoader
77
+
78
+ class FromModelLoader < ModelLoader #:nodoc
79
+ def initialize(name, opts={})
80
+ super
81
+ @load_from = "@#{opts[:from]}".to_sym
82
+ @association = name.to_s
83
+ end
84
+
85
+ def load_model(controller)
86
+ retrieve_association_through(controller, @load_from)
87
+ end
88
+ end # FromModelLoader
89
+
90
+ end # ThumbleMonks
@@ -0,0 +1,51 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = "load_model"
3
+ s.version = "0.2.2"
4
+ s.date = "2009-06-03"
5
+ s.summary = "Rails Controller plugin that provides easy and useful macros for tying models and requests together"
6
+ s.email = %w[gus@gusg.us gabriel.gironda@gmail.com]
7
+ s.homepage = "http://github.com/thumblemonks/load_model"
8
+ s.description = "Rails Controller plugin that provides easy and useful macros for tying models and requests together"
9
+ s.authors = %w[Justin\ Knowlden Gabriel\ Gironda Dan\ Hodos]
10
+
11
+ s.rubyforge_project = %q{load_model}
12
+
13
+ s.has_rdoc = true
14
+ s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Load Model", "--main", "README.markdown"]
15
+ s.extra_rdoc_files = ["HISTORY.markdown", "README.markdown"]
16
+
17
+ s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to?(:required_rubygems_version=)
18
+ s.rubygems_version = "1.3.1"
19
+ s.require_paths = ["lib"]
20
+
21
+ # run git ls-files to get an updated list
22
+ s.files = %w[
23
+ HISTORY.markdown
24
+ MIT-LICENSE
25
+ README.markdown
26
+ Rakefile
27
+ lib/load_model.rb
28
+ lib/thumblemonks/model_loader.rb
29
+ load_model.gemspec
30
+ ]
31
+
32
+ s.test_files = %w[
33
+ test/functional/basic_controller_test.rb
34
+ test/functional/from_controller_test.rb
35
+ test/functional/keys_controller_test.rb
36
+ test/functional/require_model_controller_test.rb
37
+ test/functional/restrict_options_controller_test.rb
38
+ test/functional/string_key_controller_test.rb
39
+ test/functional/through_controller_test.rb
40
+ test/rails/app/controllers/application.rb
41
+ test/rails/config/boot.rb
42
+ test/rails/config/database.yml
43
+ test/rails/config/environment.rb
44
+ test/rails/config/environments/test.rb
45
+ test/rails/config/routes.rb
46
+ test/rails/db/schema.rb
47
+ test/test_helper.rb
48
+ ]
49
+
50
+ s.post_install_message = %q{Choosy prima donnas choose Thumble Monks}
51
+ end
@@ -0,0 +1,90 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class BasicController < ActionController::Base
4
+ load_model :user
5
+ load_model :alternate, :parameter_key => :alternate_id,
6
+ :foreign_key => :alternate_id
7
+ load_model :chameleon, :class => :user
8
+ load_model :flamingo, :class => User
9
+ load_model :tucan, :class => :alternate, :parameter_key => :alternate_id,
10
+ :foreign_key => :alternate_id
11
+
12
+ def index; render :text => 'hello'; end
13
+ end
14
+
15
+ class BasicControllerTest < ActionController::TestCase
16
+ def setup
17
+ @foo = User.create!(:name => 'Foo')
18
+ end
19
+
20
+ context "when parameter" do
21
+ context "is provided" do
22
+ setup { get :index, :id => @foo.id }
23
+ should("find record") { assert_equal @foo.id, assigns(:user).id }
24
+ end # is provided
25
+
26
+ context "is not provided" do
27
+ setup { get :index }
28
+ should("not assign any record") { assert_nil assigns(:user) }
29
+ end # is not provided
30
+
31
+ context "does not match existing record" do
32
+ setup { get :index, :id => (@foo.id + 1) }
33
+ should("not assign any record") { assert_nil assigns(:user) }
34
+ end # does not match existing record
35
+ end # when parameter
36
+
37
+ should "find chameleon in users" do
38
+ get :index, :id => @foo.id
39
+ assert_equal @foo.id, assigns(:chameleon).id
40
+ end
41
+
42
+ should "not find chameleon in users with nonexistent id" do
43
+ get :index, :id => (@foo.id + 1)
44
+ assert_nil assigns(:chameleon)
45
+ end
46
+
47
+ should "not find record if key value is not an integer" do
48
+ get :index, :id => 'abc'
49
+ assert_nil assigns(:user)
50
+ end
51
+
52
+ context "when class name is constant" do
53
+ should "find flamingo in user table" do
54
+ get :index, :id => @foo.id
55
+ assert_equal @foo.id, assigns(:flamingo).id
56
+ end
57
+
58
+ should "not find flamingo in user table" do
59
+ get :index, :id => (@foo.id + 1)
60
+ assert_nil assigns(:flamingo)
61
+ end
62
+ end # when class name is constant
63
+
64
+ context "for alternate" do
65
+ context "with existing id" do
66
+ setup do
67
+ @alt = Alternate.create!(:name => 'Alternate', :alternate_id => 100)
68
+ get :index, :alternate_id => @alt.alternate_id
69
+ end
70
+
71
+ should_assign_to(:alternate) { @alt }
72
+ should_assign_to(:tucan) { @alt }
73
+ end
74
+
75
+ context "with non-existant id" do
76
+ setup { get :index, :alternate_id => 99 }
77
+ should_not_assign_to(:alternate)
78
+ should_not_assign_to(:tucan)
79
+ end
80
+ end # with alternate class and key
81
+
82
+ context "when id is nil for users" do
83
+ setup do
84
+ User.expects(:find_by_id).never
85
+ get :index, :id => ''
86
+ end
87
+
88
+ should_not_assign_to(:user)
89
+ end # when parameter value is nil
90
+ end
@@ -0,0 +1,26 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class FromController < ActionController::Base
4
+ load_model :post
5
+ load_model :user, :from => :post
6
+ load_model :foo, :from => :post
7
+
8
+ def index; render :text => 'index'; end
9
+ end
10
+
11
+ class FromControllerTest < ActionController::TestCase
12
+ def setup
13
+ @user = User.create!(:name => 'Foo')
14
+ @post = @user.posts.create!(:name => 'Foo post')
15
+ end
16
+
17
+ context "loading from post model" do
18
+ setup do
19
+ get :index, :id => @post.id
20
+ end
21
+
22
+ should_assign_to(:post) { @post }
23
+ should_assign_to(:user) { @user }
24
+ should_assign_to(:foo) { "bar" }
25
+ end
26
+ end
@@ -0,0 +1,32 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class KeysController < ActionController::Base
4
+ # Expects to use fuzzle_id as parameter key against User class with FK of :id
5
+ load_model :user, :parameter_key => :fuzzle_id
6
+
7
+ # Expects to use :fuzzle_id as FK and parameter key against Fuzzle class
8
+ # (normal operation)
9
+ load_model :fuzzler, :parameter_key => :fuzzle_id, :foreign_key => :fuzzle_id,
10
+ :class => :fuzzle
11
+
12
+ def index; render :text => 'hello'; end
13
+ end
14
+
15
+ class KeysControllerTest < ActionController::TestCase
16
+ def setup
17
+ @user = User.create!(:name => 'Foo')
18
+ @fuzzler = Fuzzle.create!(:name => 'Bar', :fuzzle_id => 300)
19
+ end
20
+
21
+ def test_should_find_user_using_fuzzle_id_as_param_key
22
+ get :index, :fuzzle_id => @user.id
23
+ assert_equal @user.id, assigns(:user).id
24
+ assert_nil assigns(:fuzzler)
25
+ end
26
+
27
+ def test_should_find_fuzzler_using_fuzzle_id_as_param_and_foreign_key
28
+ get :index, :fuzzle_id => @fuzzler.fuzzle_id
29
+ assert_equal @fuzzler.id, assigns(:fuzzler).id
30
+ assert_nil assigns(:user)
31
+ end
32
+ end
@@ -0,0 +1,50 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class RequireModelController < ActionController::Base
4
+ load_model :stuser, :class => :alternate, :parameter_key => :alternate_id,
5
+ :foreign_key => :alternate_id, :require => nil # never required
6
+ load_model :fuzzle, :parameter_key => :fuzzle_id, :foreign_key => :fuzzle_id,
7
+ :require => [:newer] # required for newer action
8
+ load_model :user, :require => true # required for all actions
9
+
10
+ def index; render :text => 'whatever'; end
11
+ def new; render :text => 'whatever 2'; end
12
+ def newer; render :text => 'whatever 3'; end
13
+ end
14
+
15
+ class RequireModelControllerTest < ActionController::TestCase
16
+ def setup
17
+ @foo = User.create!(:name => 'Foo')
18
+ end
19
+
20
+ def test_should_find_record_if_required_to_find_record_and_record_is_found
21
+ get :index, :id => @foo.id
22
+ assert_equal @foo.id, assigns(:user).id
23
+ end
24
+
25
+ def test_should_not_require_value_if_required_is_nil
26
+ get :new, :id => @foo.id
27
+ assert_equal @foo.id, assigns(:user).id
28
+ end
29
+
30
+ def test_should_not_require_value_if_required_is_for_different_action
31
+ fuzz = Fuzzle.create!(:name => 'Fuzzy', :fuzzle_id => 200)
32
+ get :new, :id => @foo.id, :fuzzle_id => fuzz.id
33
+ assert_equal @foo.id, assigns(:user).id
34
+ assert_nil assigns(:stuser)
35
+ assert_nil assigns(:fuzzle)
36
+ end
37
+
38
+ def test_should_raise_error_if_required_is_scoped_and_record_not_found
39
+ fuzz = Fuzzle.create!(:name => 'Fuzzy', :fuzzle_id => 200)
40
+ assert_raise(ThumbleMonks::LoadModel::RequiredRecordNotFound) do
41
+ get :newer, :id => @foo.id, :fuzzle_id => (fuzz.id + 1)
42
+ end
43
+ end
44
+
45
+ def test_should_raise_error_if_required_is_true_and_record_not_found
46
+ assert_raise(ThumbleMonks::LoadModel::RequiredRecordNotFound) do
47
+ get :new, :id => (@foo.id + 1)
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,37 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class RestrictOptionsController < ActionController::Base
4
+ load_model :user, :only => [:index]
5
+ load_model :alternate, :except => [:index], :parameter_key => :alternate_id,
6
+ :foreign_key => :alternate_id
7
+
8
+ def index; render :text => 'ran index'; end
9
+ def show; render :text => 'ran show'; end
10
+ end
11
+
12
+ class RestrictOptionsControllerTest < ActionController::TestCase
13
+ def setup
14
+ @foo = User.create!(:name => 'Foo')
15
+ @alt = Alternate.create!(:name => 'Bar', :alternate_id => 100)
16
+ end
17
+
18
+ def test_should_load_user_for_index
19
+ get :index, :id => @foo.id, :alternate_id => @alt.id
20
+ assert_equal @foo.id, assigns(:user).id
21
+ end
22
+
23
+ def test_should_not_load_alternate_for_index
24
+ get :index, :id => @foo.id, :alternate_id => @alt.alternate_id
25
+ assert_nil assigns(:alternate)
26
+ end
27
+
28
+ def test_should_load_alternate_for_show
29
+ get :show, :id => @foo.id, :alternate_id => @alt.alternate_id
30
+ assert_equal @alt, assigns(:alternate)
31
+ end
32
+
33
+ def test_should_not_load_user_for_show
34
+ get :show, :id => @foo.id, :alternate_id => @alt.alternate_id
35
+ assert_nil assigns(:user)
36
+ end
37
+ end
@@ -0,0 +1,54 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class StringKeyController < ActionController::Base
4
+ load_model 'user'
5
+ load_model 'alternate', :parameter_key => 'alternate_id',
6
+ :foreign_key => 'alternate_id'
7
+ load_model 'chameleon', :class => 'user'
8
+
9
+ def index; render :text => 'goodbye'; end
10
+ end
11
+
12
+ class StringKeyControllerTest < ActionController::TestCase
13
+ def setup
14
+ @foo = User.create!(:name => 'Foo')
15
+ end
16
+
17
+ def test_should_find_record_and_assign_to_instance_variable_if_param_provided
18
+ get :index, :id => @foo.id
19
+ assert_equal @foo.id, assigns(:user).id
20
+ end
21
+
22
+ def test_should_return_nil_if_expected_param_not_provided
23
+ get :index
24
+ assert_nil assigns(:user)
25
+ end
26
+
27
+ def test_should_return_nil_if_expected_param_does_not_match_record
28
+ get :index, :id => (@foo.id + 1) # Should not belong to an existing user
29
+ assert_nil assigns(:user)
30
+ end
31
+
32
+ def test_should_find_record_with_alternate_id_as_expected_param_key
33
+ alt = Alternate.create!(:name => 'Alternate', :alternate_id => 100)
34
+ get :index, :alternate_id => alt.alternate_id
35
+ assert_equal alt.id, assigns(:alternate).id
36
+ assert_equal alt.alternate_id, assigns(:alternate).alternate_id
37
+ end
38
+
39
+ def test_should_find_nothing_when_alternate_id_does_not_match_record
40
+ alt = Alternate.create!(:name => 'Alternate', :alternate_id => 99)
41
+ get :index, :alternate_id => 100
42
+ assert_nil assigns(:alternate)
43
+ end
44
+
45
+ def test_should_find_chameleon_in_user_table
46
+ get :index, :id => @foo.id
47
+ assert_equal @foo.id, assigns(:chameleon).id
48
+ end
49
+
50
+ def test_should_not_find_chameleon_in_user_table_with_nonexistent_id
51
+ get :index, :id => (@foo.id + 1)
52
+ assert_nil assigns(:chameleon)
53
+ end
54
+ end
@@ -0,0 +1,80 @@
1
+ require File.dirname(__FILE__) + '/../test_helper'
2
+
3
+ class ThroughController < ActionController::Base
4
+ load_model :user, :parameter_key => :user_id
5
+ load_model :post, :through => :user, :except => [:show]
6
+ # proving that except and only work
7
+ load_model :post, :through => :user, :parameter_key => 'weird_id',
8
+ :require => true, :only => [:show]
9
+
10
+ load_model :post, :through => :user, :association => :unpublished_posts,
11
+ :require => true, :only => [:show_unpublished]
12
+
13
+ def index; render :text => 'index'; end
14
+ def show; render :text => 'show'; end
15
+ def show_unpublished; render :text => 'unpublished'; end
16
+ end
17
+
18
+ class ThroughControllerTest < ActionController::TestCase
19
+ def setup
20
+ @user = User.create!(:name => 'Foo')
21
+ @post = @user.posts.create!(:name => 'Foo post')
22
+ end
23
+
24
+ context "index with valid ids" do
25
+ setup do
26
+ get :index, :user_id => @user.id, :id => @post.id
27
+ end
28
+
29
+ should_assign_to(:user) { @user }
30
+ should_assign_to(:post) { @post }
31
+ end # with valid ids
32
+
33
+ context "show_unpublished with valid id" do
34
+ setup do
35
+ @unpublished_post = @user.posts.create!{ |p| p.published = false }
36
+ get :show_unpublished, :user_id => @user.id, :id => @unpublished_post.id
37
+ end
38
+
39
+ should_assign_to(:user) { @user }
40
+ should_assign_to(:post) { @unpublished_post }
41
+ end
42
+
43
+ context "index with invalid post id" do
44
+ setup do
45
+ get :index, :user_id => @user.id, :id => -1
46
+ end
47
+
48
+ should_assign_to(:user) { @user }
49
+ should_not_assign_to :post
50
+ end # with invalid post id
51
+
52
+ context "show with alternative post via weird_id" do
53
+ context "has exisiting records" do
54
+ setup do
55
+ get :show, :user_id => @user.id, :weird_id => @post.id
56
+ end
57
+
58
+ should_assign_to(:user) { @user }
59
+ should_assign_to(:post) { @post }
60
+ end # has existing records
61
+
62
+ context "has nonexistent records for required action" do
63
+ should "flail with exception" do
64
+ assert_raise(ThumbleMonks::LoadModel::RequiredRecordNotFound) do
65
+ get :show, :user_id => @user.id, :weird_id => -1
66
+ end
67
+ end
68
+ end # has nonexistant records for required action
69
+ end # show with alternative post via weird_id
70
+
71
+ context "when parameter value is nil" do
72
+ setup do
73
+ Post.expects(:find_by_id).never
74
+ get :index, :user_id => @user.id, :id => ''
75
+ end
76
+
77
+ should_assign_to(:user) { @user }
78
+ should_not_assign_to(:post)
79
+ end # when parameter value is nil
80
+ end
@@ -0,0 +1,3 @@
1
+ class ApplicationController < ActionController::Base
2
+ # We don't put any other controllers in this directory because load_model loads too late
3
+ end
@@ -0,0 +1,109 @@
1
+ # Don't change this file!
2
+ # Configure your app in config/environment.rb and config/environments/*.rb
3
+
4
+ RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
5
+
6
+ module Rails
7
+ class << self
8
+ def boot!
9
+ unless booted?
10
+ preinitialize
11
+ pick_boot.run
12
+ end
13
+ end
14
+
15
+ def booted?
16
+ defined? Rails::Initializer
17
+ end
18
+
19
+ def pick_boot
20
+ (vendor_rails? ? VendorBoot : GemBoot).new
21
+ end
22
+
23
+ def vendor_rails?
24
+ File.exist?("#{RAILS_ROOT}/vendor/rails")
25
+ end
26
+
27
+ def preinitialize
28
+ load(preinitializer_path) if File.exist?(preinitializer_path)
29
+ end
30
+
31
+ def preinitializer_path
32
+ "#{RAILS_ROOT}/config/preinitializer.rb"
33
+ end
34
+ end
35
+
36
+ class Boot
37
+ def run
38
+ load_initializer
39
+ Rails::Initializer.run(:set_load_path)
40
+ end
41
+ end
42
+
43
+ class VendorBoot < Boot
44
+ def load_initializer
45
+ require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
46
+ Rails::Initializer.run(:install_gem_spec_stubs)
47
+ end
48
+ end
49
+
50
+ class GemBoot < Boot
51
+ def load_initializer
52
+ self.class.load_rubygems
53
+ load_rails_gem
54
+ require 'initializer'
55
+ end
56
+
57
+ def load_rails_gem
58
+ if version = self.class.gem_version
59
+ gem 'rails', version
60
+ else
61
+ gem 'rails'
62
+ end
63
+ rescue Gem::LoadError => load_error
64
+ $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
65
+ exit 1
66
+ end
67
+
68
+ class << self
69
+ def rubygems_version
70
+ Gem::RubyGemsVersion rescue nil
71
+ end
72
+
73
+ def gem_version
74
+ if defined? RAILS_GEM_VERSION
75
+ RAILS_GEM_VERSION
76
+ elsif ENV.include?('RAILS_GEM_VERSION')
77
+ ENV['RAILS_GEM_VERSION']
78
+ else
79
+ parse_gem_version(read_environment_rb)
80
+ end
81
+ end
82
+
83
+ def load_rubygems
84
+ require 'rubygems'
85
+ min_version = '1.3.1'
86
+ unless rubygems_version >= min_version
87
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
88
+ exit 1
89
+ end
90
+
91
+ rescue LoadError
92
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
93
+ exit 1
94
+ end
95
+
96
+ def parse_gem_version(text)
97
+ $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
98
+ end
99
+
100
+ private
101
+ def read_environment_rb
102
+ File.read("#{RAILS_ROOT}/config/environment.rb")
103
+ end
104
+ end
105
+ end
106
+ end
107
+
108
+ # All that for this:
109
+ Rails.boot!
@@ -0,0 +1,3 @@
1
+ test:
2
+ adapter: sqlite3
3
+ database: ":memory:"
@@ -0,0 +1,15 @@
1
+ # Specifies gem version of Rails to use when vendor/rails is not present
2
+ RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
3
+
4
+ # Bootstrap the Rails environment, frameworks, and default configuration
5
+ require File.join(File.dirname(__FILE__), 'boot')
6
+
7
+ Rails::Initializer.run do |config|
8
+ config.gem 'thoughtbot-shoulda', :lib => 'shoulda/rails', :source => 'http://gems.github.com'
9
+ config.gem 'mocha'
10
+
11
+ config.action_controller.session = {
12
+ :session_key => '_load_model_session',
13
+ :secret => '9908cd9908cd9908cd9908cd9908cd9908cd9908cd9908cd9908cd9908cd9908cd9908cd9908cd'
14
+ }
15
+ end
@@ -0,0 +1,19 @@
1
+ # Settings specified here will take precedence over those in config/environment.rb
2
+
3
+ # The test environment is used exclusively to run your application's
4
+ # test suite. You never need to work with it otherwise. Remember that
5
+ # your test database is "scratch space" for the test suite and is wiped
6
+ # and recreated between test runs. Don't rely on the data there!
7
+ config.cache_classes = true
8
+
9
+ # Log error messages when you accidentally call methods on nil.
10
+ config.whiny_nils = true
11
+
12
+ # Show full error reports and disable caching
13
+ config.action_controller.consider_all_requests_local = true
14
+ config.action_controller.perform_caching = false
15
+
16
+ # Tell ActionMailer not to deliver emails to the real world.
17
+ # The :test delivery method accumulates sent emails in the
18
+ # ActionMailer::Base.deliveries array.
19
+ config.action_mailer.delivery_method = :test
@@ -0,0 +1,5 @@
1
+ ActionController::Routing::Routes.draw do |map|
2
+ map.connect ':controller/service.wsdl', :action => 'wsdl'
3
+ map.connect ':controller/:action/:id.:format'
4
+ map.connect ':controller/:action/:id'
5
+ end
@@ -0,0 +1,21 @@
1
+ ActiveRecord::Schema.define(:version => 1) do
2
+ create_table 'users', :force => true do |t|
3
+ t.column :name, :string
4
+ end
5
+
6
+ create_table 'posts', :force => true do |t|
7
+ t.column :user_id, :integer
8
+ t.column :published, :boolean, :default => true
9
+ t.column :name, :string
10
+ end
11
+
12
+ create_table 'alternates', :force => true do |t|
13
+ t.column :alternate_id, :integer
14
+ t.column :name, :string
15
+ end
16
+
17
+ create_table 'fuzzles', :force => true do |t|
18
+ t.column :fuzzle_id, :integer
19
+ t.column :name, :string
20
+ end
21
+ end
@@ -0,0 +1,26 @@
1
+ def require_local_lib(pattern)
2
+ Dir.glob(File.join(File.dirname(__FILE__), pattern)).each {|f| require f }
3
+ end
4
+
5
+ ENV["RAILS_ENV"] = "test"
6
+ ENV["RAILS_ROOT"] = File.expand_path(File.join(File.dirname(__FILE__), '..', 'test', 'rails'))
7
+
8
+ require File.expand_path(File.join(ENV["RAILS_ROOT"], 'config', 'environment'))
9
+ require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'load_model'))
10
+ require 'test_help'
11
+
12
+ load(File.join(ENV["RAILS_ROOT"], "db", "schema.rb"))
13
+
14
+ # Models
15
+
16
+ class User < ActiveRecord::Base
17
+ has_many :posts, :conditions => {:published => true}
18
+ has_many :unpublished_posts, :conditions => {:published => false}, :class_name => 'Post'
19
+ end
20
+ class Post < ActiveRecord::Base
21
+ belongs_to :user
22
+
23
+ def foo; "bar"; end
24
+ end
25
+ class Alternate < ActiveRecord::Base; end
26
+ class Fuzzle < ActiveRecord::Base; end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: load_model
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.2
5
+ platform: ruby
6
+ authors:
7
+ - Justin Knowlden
8
+ - Gabriel Gironda
9
+ - Dan Hodos
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+
14
+ date: 2009-06-03 00:00:00 -05:00
15
+ default_executable:
16
+ dependencies: []
17
+
18
+ description: Rails Controller plugin that provides easy and useful macros for tying models and requests together
19
+ email:
20
+ - gus@gusg.us
21
+ - gabriel.gironda@gmail.com
22
+ executables: []
23
+
24
+ extensions: []
25
+
26
+ extra_rdoc_files:
27
+ - HISTORY.markdown
28
+ - README.markdown
29
+ files:
30
+ - HISTORY.markdown
31
+ - MIT-LICENSE
32
+ - README.markdown
33
+ - Rakefile
34
+ - lib/load_model.rb
35
+ - lib/thumblemonks/model_loader.rb
36
+ - load_model.gemspec
37
+ has_rdoc: true
38
+ homepage: http://github.com/thumblemonks/load_model
39
+ licenses: []
40
+
41
+ post_install_message: Choosy prima donnas choose Thumble Monks
42
+ rdoc_options:
43
+ - --line-numbers
44
+ - --inline-source
45
+ - --title
46
+ - Load Model
47
+ - --main
48
+ - README.markdown
49
+ require_paths:
50
+ - lib
51
+ required_ruby_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: "0"
56
+ version:
57
+ required_rubygems_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: "1.2"
62
+ version:
63
+ requirements: []
64
+
65
+ rubyforge_project: load_model
66
+ rubygems_version: 1.3.5
67
+ signing_key:
68
+ specification_version: 3
69
+ summary: Rails Controller plugin that provides easy and useful macros for tying models and requests together
70
+ test_files:
71
+ - test/functional/basic_controller_test.rb
72
+ - test/functional/from_controller_test.rb
73
+ - test/functional/keys_controller_test.rb
74
+ - test/functional/require_model_controller_test.rb
75
+ - test/functional/restrict_options_controller_test.rb
76
+ - test/functional/string_key_controller_test.rb
77
+ - test/functional/through_controller_test.rb
78
+ - test/rails/app/controllers/application.rb
79
+ - test/rails/config/boot.rb
80
+ - test/rails/config/database.yml
81
+ - test/rails/config/environment.rb
82
+ - test/rails/config/environments/test.rb
83
+ - test/rails/config/routes.rb
84
+ - test/rails/db/schema.rb
85
+ - test/test_helper.rb