without_instanciation 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/README.rdoc ADDED
@@ -0,0 +1,42 @@
1
+ == Summary
2
+
3
+ On large results of ActiveRecord queries, instanciation + GC of objects has a real cost of
4
+ allocating memory, setting values, and after all GC garbage ...
5
+
6
+ Inside a without_instanciation block, data is returned as hash of values.
7
+ Objects instanciation process id skipped and though GC of theses objects too.
8
+
9
+ Performance up to 60% for large query results.
10
+
11
+ Of course, you no longer work with Ruby AR objects in this block.
12
+
13
+ == Usage
14
+
15
+ users = User.without_instanciation { User.all }
16
+
17
+ #users is a array of hashes where each key is a User attribute
18
+
19
+ users.first['name'] #=> user name
20
+
21
+
22
+ Inside the model :
23
+
24
+ users = without_instanciation do
25
+ where(:name => "Matt")
26
+ end
27
+ users.first['name'] #=> "Matt"
28
+
29
+ == Install
30
+ #in your Gemfile
31
+
32
+ gem 'without_instanciation'
33
+
34
+
35
+ == MIT Licence
36
+ Copyright (c) 2012 Cantin Philippe
37
+
38
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
39
+
40
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
41
+
42
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,35 @@
1
+ module ActiveRecord
2
+ class Base
3
+ class << self
4
+ def without_instanciation opt={}
5
+ eigenclass = (class << self; self end)
6
+ Psychanalyst.redefine(eigenclass, :find_by_sql) do |sql|
7
+ connection.select_all(sanitize_sql(sql), "#{name} Load")
8
+ end
9
+ result = yield
10
+ Psychanalyst.undefine(eigenclass, :find_by_sql)
11
+ result
12
+ end
13
+ end
14
+ end
15
+ end
16
+
17
+ module Psychanalyst
18
+
19
+ def self.redefine klass, method, &block
20
+ klass.send(:alias_method, original_method(method), method)
21
+ klass.send(:define_method, method) do |*params|
22
+ instance_exec(*params, &block)
23
+ end
24
+ end
25
+
26
+ def self.undefine klass, method
27
+ klass.send(:undef_method, method)
28
+ klass.send(:alias_method, method, original_method(method))
29
+ end
30
+
31
+ def self.original_method method
32
+ ('original_' + method.to_s).to_sym
33
+ end
34
+
35
+ end
@@ -0,0 +1,3 @@
1
+ module WithoutInstanciation
2
+ VERSION = "1.0.0"
3
+ end
@@ -0,0 +1,3 @@
1
+ class ApplicationController < ActionController::Base
2
+ protect_from_forgery
3
+ end
@@ -0,0 +1,2 @@
1
+ module ApplicationHelper
2
+ end
@@ -0,0 +1,2 @@
1
+ class User < ActiveRecord::Base
2
+ end
@@ -0,0 +1,44 @@
1
+ require File.expand_path('../boot', __FILE__)
2
+
3
+ require "active_model/railtie"
4
+ require "active_record/railtie"
5
+ require "action_controller/railtie"
6
+ require "action_view/railtie"
7
+ require "action_mailer/railtie"
8
+
9
+ Bundler.require
10
+
11
+ module Dummy
12
+ class Application < Rails::Application
13
+ # Settings in config/environments/* take precedence over those specified here.
14
+ # Application configuration should go into files in config/initializers
15
+ # -- all .rb files in that directory are automatically loaded.
16
+
17
+ # Custom directories with classes and modules you want to be autoloadable.
18
+ # config.autoload_paths += %W(#{config.root}/extras)
19
+
20
+ # Only load the plugins named here, in the order given (default is alphabetical).
21
+ # :all can be used as a placeholder for all plugins not explicitly named.
22
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
23
+
24
+ # Activate observers that should always be running.
25
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
26
+
27
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
28
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
29
+ # config.time_zone = 'Central Time (US & Canada)'
30
+
31
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
32
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
33
+ # config.i18n.default_locale = :de
34
+
35
+ # JavaScript files you want as :defaults (application.js is always included).
36
+ # config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
37
+
38
+ # Configure the default encoding used in templates for Ruby 1.9.
39
+ config.encoding = "utf-8"
40
+
41
+ # Configure sensitive parameters which will be filtered from the log file.
42
+ config.filter_parameters += [:password]
43
+ end
44
+ end
@@ -0,0 +1,10 @@
1
+ require 'rubygems'
2
+ gemfile = File.expand_path('../../../../Gemfile', __FILE__)
3
+
4
+ if File.exist?(gemfile)
5
+ ENV['BUNDLE_GEMFILE'] = gemfile
6
+ require 'bundler'
7
+ Bundler.setup
8
+ end
9
+
10
+ $:.unshift File.expand_path('../../../../lib', __FILE__)
@@ -0,0 +1,5 @@
1
+ # Load the rails application
2
+ require File.expand_path('../application', __FILE__)
3
+
4
+ # Initialize the rails application
5
+ Dummy::Application.initialize!
@@ -0,0 +1,26 @@
1
+ Dummy::Application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb
3
+
4
+ # In the development environment your application's code is reloaded on
5
+ # every request. This slows down response time but is perfect for development
6
+ # since you don't have to restart the webserver when you make code changes.
7
+ config.cache_classes = false
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.consider_all_requests_local = true
14
+ config.action_view.debug_rjs = true
15
+ config.action_controller.perform_caching = false
16
+
17
+ # Don't care if the mailer can't send
18
+ config.action_mailer.raise_delivery_errors = false
19
+
20
+ # Print deprecation notices to the Rails logger
21
+ config.active_support.deprecation = :log
22
+
23
+ # Only use best-standards-support built into browsers
24
+ config.action_dispatch.best_standards_support = :builtin
25
+ end
26
+
@@ -0,0 +1,49 @@
1
+ Dummy::Application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb
3
+
4
+ # The production environment is meant for finished, "live" apps.
5
+ # Code is not reloaded between requests
6
+ config.cache_classes = true
7
+
8
+ # Full error reports are disabled and caching is turned on
9
+ config.consider_all_requests_local = false
10
+ config.action_controller.perform_caching = true
11
+
12
+ # Specifies the header that your server uses for sending files
13
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
14
+
15
+ # For nginx:
16
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
17
+
18
+ # If you have no front-end server that supports something like X-Sendfile,
19
+ # just comment this out and Rails will serve the files
20
+
21
+ # See everything in the log (default is :info)
22
+ # config.log_level = :debug
23
+
24
+ # Use a different logger for distributed setups
25
+ # config.logger = SyslogLogger.new
26
+
27
+ # Use a different cache store in production
28
+ # config.cache_store = :mem_cache_store
29
+
30
+ # Disable Rails's static asset server
31
+ # In production, Apache or nginx will already do this
32
+ config.serve_static_assets = false
33
+
34
+ # Enable serving of images, stylesheets, and javascripts from an asset server
35
+ # config.action_controller.asset_host = "http://assets.example.com"
36
+
37
+ # Disable delivery errors, bad email addresses will be ignored
38
+ # config.action_mailer.raise_delivery_errors = false
39
+
40
+ # Enable threaded mode
41
+ # config.threadsafe!
42
+
43
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
44
+ # the I18n.default_locale when a translation can not be found)
45
+ config.i18n.fallbacks = true
46
+
47
+ # Send deprecation notices to registered listeners
48
+ config.active_support.deprecation = :notify
49
+ end
@@ -0,0 +1,35 @@
1
+ Dummy::Application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb
3
+
4
+ # The test environment is used exclusively to run your application's
5
+ # test suite. You never need to work with it otherwise. Remember that
6
+ # your test database is "scratch space" for the test suite and is wiped
7
+ # and recreated between test runs. Don't rely on the data there!
8
+ config.cache_classes = true
9
+
10
+ # Log error messages when you accidentally call methods on nil.
11
+ config.whiny_nils = true
12
+
13
+ # Show full error reports and disable caching
14
+ config.consider_all_requests_local = true
15
+ config.action_controller.perform_caching = false
16
+
17
+ # Raise exceptions instead of rendering exception templates
18
+ config.action_dispatch.show_exceptions = false
19
+
20
+ # Disable request forgery protection in test environment
21
+ config.action_controller.allow_forgery_protection = false
22
+
23
+ # Tell Action Mailer not to deliver emails to the real world.
24
+ # The :test delivery method accumulates sent emails in the
25
+ # ActionMailer::Base.deliveries array.
26
+ config.action_mailer.delivery_method = :test
27
+
28
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
29
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
30
+ # like if you have constraints or database-specific column types
31
+ # config.active_record.schema_format = :sql
32
+
33
+ # Print deprecation notices to the stderr
34
+ config.active_support.deprecation = :stderr
35
+ end
@@ -0,0 +1,7 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4
+ # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5
+
6
+ # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7
+ # Rails.backtrace_cleaner.remove_silencers!
@@ -0,0 +1,10 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Add new inflection rules using the following format
4
+ # (all these examples are active by default):
5
+ # ActiveSupport::Inflector.inflections do |inflect|
6
+ # inflect.plural /^(ox)$/i, '\1en'
7
+ # inflect.singular /^(ox)en/i, '\1'
8
+ # inflect.irregular 'person', 'people'
9
+ # inflect.uncountable %w( fish sheep )
10
+ # end
@@ -0,0 +1,5 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Add new mime types for use in respond_to blocks:
4
+ # Mime::Type.register "text/richtext", :rtf
5
+ # Mime::Type.register_alias "text/html", :iphone
@@ -0,0 +1,7 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Your secret key for verifying the integrity of signed cookies.
4
+ # If you change this key, all old signed cookies will become invalid!
5
+ # Make sure the secret is at least 30 characters and all random,
6
+ # no regular words or you'll be exposed to dictionary attacks.
7
+ Dummy::Application.config.secret_token = '6a652019947cecf299f8b70ffb26d4333bb36c94f54887eecdd6e73faea83e80de987b6d3af682f8a2be596366c9185edb2cc5ab5ff0cc9a865818a3aefa4e70'
@@ -0,0 +1,8 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ Dummy::Application.config.session_store :cookie_store, :key => '_dummy_session'
4
+
5
+ # Use the database for sessions instead of the cookie-based default,
6
+ # which shouldn't be used to store highly confidential information
7
+ # (create the session table with "rails generate session_migration")
8
+ # Dummy::Application.config.session_store :active_record_store
@@ -0,0 +1,58 @@
1
+ Dummy::Application.routes.draw do
2
+ # The priority is based upon order of creation:
3
+ # first created -> highest priority.
4
+
5
+ # Sample of regular route:
6
+ # match 'products/:id' => 'catalog#view'
7
+ # Keep in mind you can assign values other than :controller and :action
8
+
9
+ # Sample of named route:
10
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
11
+ # This route can be invoked with purchase_url(:id => product.id)
12
+
13
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
14
+ # resources :products
15
+
16
+ # Sample resource route with options:
17
+ # resources :products do
18
+ # member do
19
+ # get 'short'
20
+ # post 'toggle'
21
+ # end
22
+ #
23
+ # collection do
24
+ # get 'sold'
25
+ # end
26
+ # end
27
+
28
+ # Sample resource route with sub-resources:
29
+ # resources :products do
30
+ # resources :comments, :sales
31
+ # resource :seller
32
+ # end
33
+
34
+ # Sample resource route with more complex sub-resources
35
+ # resources :products do
36
+ # resources :comments
37
+ # resources :sales do
38
+ # get 'recent', :on => :collection
39
+ # end
40
+ # end
41
+
42
+ # Sample resource route within a namespace:
43
+ # namespace :admin do
44
+ # # Directs /admin/products/* to Admin::ProductsController
45
+ # # (app/controllers/admin/products_controller.rb)
46
+ # resources :products
47
+ # end
48
+
49
+ # You can have the root of your site routed with "root"
50
+ # just remember to delete public/index.html.
51
+ # root :to => "welcome#index"
52
+
53
+ # See how all your routes lay out with "rake routes"
54
+
55
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
56
+ # Note: This route will make all actions in every controller accessible via GET requests.
57
+ # match ':controller(/:action(/:id(.:format)))'
58
+ end
@@ -0,0 +1,12 @@
1
+ class CreateUsers < ActiveRecord::Migration
2
+ def self.up
3
+ create_table :users do |t|
4
+ t.string :name
5
+ t.timestamps
6
+ end
7
+ end
8
+
9
+ def self.down
10
+ drop_table :users
11
+ end
12
+ end
@@ -0,0 +1,21 @@
1
+ # This file is auto-generated from the current state of the database. Instead
2
+ # of editing this file, please use the migrations feature of Active Record to
3
+ # incrementally modify your database, and then regenerate this schema definition.
4
+ #
5
+ # Note that this schema.rb definition is the authoritative source for your
6
+ # database schema. If you need to create the application database on another
7
+ # system, you should be using db:schema:load, not running all the migrations
8
+ # from scratch. The latter is a flawed and unsustainable approach (the more migrations
9
+ # you'll amass, the slower it'll run and the greater likelihood for issues).
10
+ #
11
+ # It's strongly recommended to check this file into your version control system.
12
+
13
+ ActiveRecord::Schema.define(:version => 20120228153737) do
14
+
15
+ create_table "users", :force => true do |t|
16
+ t.string "name"
17
+ t.datetime "created_at"
18
+ t.datetime "updated_at"
19
+ end
20
+
21
+ end
@@ -0,0 +1,9 @@
1
+ # Configure Rails Envinronment
2
+ ENV["RAILS_ENV"] = "test"
3
+
4
+ require File.expand_path("../dummy/config/environment.rb", __FILE__)
5
+ require "rails/test_help"
6
+
7
+ # Run any available migration
8
+ ActiveRecord::Migrator.migrate File.expand_path("../dummy/db/migrate/", __FILE__)
9
+
@@ -0,0 +1,31 @@
1
+ require 'test_helper'
2
+
3
+ class WithoutInstanciationTest < ActiveSupport::TestCase
4
+
5
+ setup do |variable|
6
+ (1..10).each { |n| User.create!(:name => "Number #{n}") }
7
+ end
8
+
9
+ test "it should get all users" do
10
+ users = User.without_instanciation { User.all }
11
+
12
+ assert_equal 10, users.count
13
+ end
14
+
15
+ test "it should get each as Hash, not User object" do
16
+ users = User.without_instanciation { User.all }
17
+ user = users.first
18
+
19
+ assert_equal Hash, user.class
20
+ assert_equal "Number 1", user['name']
21
+ end
22
+
23
+ test "it should work fine with where query" do
24
+ users = User.without_instanciation { User.where(:name => "Number 10") }
25
+
26
+ assert_equal 1, users.count
27
+ assert_equal "Number 10", users.first['name']
28
+ end
29
+
30
+
31
+ end
metadata ADDED
@@ -0,0 +1,132 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: without_instanciation
3
+ version: !ruby/object:Gem::Version
4
+ hash: 23
5
+ prerelease:
6
+ segments:
7
+ - 1
8
+ - 0
9
+ - 0
10
+ version: 1.0.0
11
+ platform: ruby
12
+ authors:
13
+ - Philippe Cantin
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2012-02-28 00:00:00 Z
19
+ dependencies:
20
+ - !ruby/object:Gem::Dependency
21
+ name: enginex
22
+ prerelease: false
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ none: false
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ hash: 3
29
+ segments:
30
+ - 0
31
+ version: "0"
32
+ type: :development
33
+ version_requirements: *id001
34
+ - !ruby/object:Gem::Dependency
35
+ name: sqlite3
36
+ prerelease: false
37
+ requirement: &id002 !ruby/object:Gem::Requirement
38
+ none: false
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ hash: 3
43
+ segments:
44
+ - 0
45
+ version: "0"
46
+ type: :development
47
+ version_requirements: *id002
48
+ description: " On large results of ActiveRecord queries, instanciation + GC of objects has a real cost of\n allocating memory, setting values, and after all GC garbage ...\n Inside a without_instanciation block, data is returned as hash of values.\n Objects instanciation process id skipped and though GC of theses objects too.\n Performance up to 80% for large query result.\n Of course, you no longer work with Ruby AR objects in this block.\n"
49
+ email:
50
+ - anoiaque@gmail.com
51
+ executables: []
52
+
53
+ extensions: []
54
+
55
+ extra_rdoc_files:
56
+ - README.rdoc
57
+ files:
58
+ - lib/without_instanciation/version.rb
59
+ - lib/without_instanciation.rb
60
+ - README.rdoc
61
+ - test/dummy/app/controllers/application_controller.rb
62
+ - test/dummy/app/helpers/application_helper.rb
63
+ - test/dummy/app/models/user.rb
64
+ - test/dummy/config/application.rb
65
+ - test/dummy/config/boot.rb
66
+ - test/dummy/config/environment.rb
67
+ - test/dummy/config/environments/development.rb
68
+ - test/dummy/config/environments/production.rb
69
+ - test/dummy/config/environments/test.rb
70
+ - test/dummy/config/initializers/backtrace_silencers.rb
71
+ - test/dummy/config/initializers/inflections.rb
72
+ - test/dummy/config/initializers/mime_types.rb
73
+ - test/dummy/config/initializers/secret_token.rb
74
+ - test/dummy/config/initializers/session_store.rb
75
+ - test/dummy/config/routes.rb
76
+ - test/dummy/db/migrate/20120228153737_create_users.rb
77
+ - test/dummy/db/schema.rb
78
+ - test/test_helper.rb
79
+ - test/unit/without_instanciation_test.rb
80
+ homepage: ""
81
+ licenses: []
82
+
83
+ post_install_message:
84
+ rdoc_options: []
85
+
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ none: false
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ hash: 3
94
+ segments:
95
+ - 0
96
+ version: "0"
97
+ required_rubygems_version: !ruby/object:Gem::Requirement
98
+ none: false
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ hash: 3
103
+ segments:
104
+ - 0
105
+ version: "0"
106
+ requirements: []
107
+
108
+ rubyforge_project: without_instanciation
109
+ rubygems_version: 1.8.10
110
+ signing_key:
111
+ specification_version: 3
112
+ summary: Retrieve data with ActiveRecord without objects instanciations
113
+ test_files:
114
+ - test/dummy/app/controllers/application_controller.rb
115
+ - test/dummy/app/helpers/application_helper.rb
116
+ - test/dummy/app/models/user.rb
117
+ - test/dummy/config/application.rb
118
+ - test/dummy/config/boot.rb
119
+ - test/dummy/config/environment.rb
120
+ - test/dummy/config/environments/development.rb
121
+ - test/dummy/config/environments/production.rb
122
+ - test/dummy/config/environments/test.rb
123
+ - test/dummy/config/initializers/backtrace_silencers.rb
124
+ - test/dummy/config/initializers/inflections.rb
125
+ - test/dummy/config/initializers/mime_types.rb
126
+ - test/dummy/config/initializers/secret_token.rb
127
+ - test/dummy/config/initializers/session_store.rb
128
+ - test/dummy/config/routes.rb
129
+ - test/dummy/db/migrate/20120228153737_create_users.rb
130
+ - test/dummy/db/schema.rb
131
+ - test/test_helper.rb
132
+ - test/unit/without_instanciation_test.rb