Commit 497b191

mo khan <mo@mokhan.ca>
2014-04-06 23:43:03
load dependencies using inversion of control container.
1 parent c70bb91
app/controllers/application_controller.rb
@@ -2,4 +2,8 @@ class ApplicationController < ActionController::Base
   # Prevent CSRF attacks by raising an exception.
   # For APIs, you may want to use :null_session instead.
   protect_from_forgery with: :exception
+
+  def resolve(key)
+    Spank::IOC.resolve(key)
+  end
 end
app/controllers/logins_controller.rb
@@ -1,14 +1,22 @@
 class LoginsController < ApplicationController
+  before_filter :load_dependencies
+
   def new
     render nothing: true
   end
 
   def create
-    if LoginCommand.new.run(params)
+    if @login_command.run(params)
       redirect_to dashboard_path
     else
       flash[:error] = I18n.translate(:invalid_credentials)
       render :new
     end
   end
+
+  private
+
+  def load_dependencies(login_command = resolve(:login_command))
+    @login_command = login_command
+  end
 end
config/initializers/container_configuration.rb
@@ -0,0 +1,5 @@
+container = Spank::Container.new
+container.register(:login_command) do |builder|
+  LoginCommand.new(User)
+end
+Spank::IOC.bind_to(container)
Gemfile
@@ -34,6 +34,7 @@ end
 
 # Use ActiveModel has_secure_password
 gem 'bcrypt', '~> 3.1.7'
+gem 'spank'
 
 # Use unicorn as the app server
 # gem 'unicorn'
Gemfile.lock
@@ -95,6 +95,7 @@ GEM
     sdoc (0.4.0)
       json (~> 1.8)
       rdoc (~> 4.0, < 5.0)
+    spank (0.0.1393558686)
     sprockets (2.11.0)
       hike (~> 1.2)
       multi_json (~> 1.0)
@@ -131,6 +132,7 @@ DEPENDENCIES
   rspec-rails
   sass-rails (~> 4.0.2)
   sdoc
+  spank
   sqlite3
   turbolinks
   uglifier (>= 1.3.0)