Skip to content

Commit

Permalink
optimizing record creation by using method_missing instead of generat…
Browse files Browse the repository at this point in the history
…ing attribute accessors for each record
  • Loading branch information
ryanb committed Sep 1, 2008
1 parent 61e7e35 commit 1c10123
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 14 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
@@ -1,3 +1,5 @@
* performance improvements

* improving inline documentation

*0.2.1* (August 30th, 2008)
Expand Down
32 changes: 21 additions & 11 deletions lib/populator/record.rb
Expand Up @@ -3,8 +3,7 @@ module Populator
class Record
attr_accessor :attributes

# Creates a new instance of Record and generates some accessor
# methods for setting attributes. Some attributes are set by default:
# Creates a new instance of Record. Some attributes are set by default:
#
# * <tt>id</tt> - defaults to id passed
# * <tt>created_at</tt> - defaults to current time
Expand All @@ -21,23 +20,34 @@ def initialize(model_class, id)
if column == 'created_on' || column == 'updated_on'
@attributes[column.to_sym] = Date.today
end
self.instance_eval <<-EOS
def #{column}=(value)
@attributes[:#{column}] = Populator.interpret_value(value)
end
def #{column}
@attributes[:#{column}]
end
EOS
end
end

# override id since method_missing won't catch this column name
def id
@attributes[:id]
end

# Return values for all columns inside an array.
def attribute_values
@columns.map do |column|
@attributes[column.to_sym]
end
end

private

def method_missing(sym, *args, &block)
name = sym.to_s
if @columns.include?(name.sub('=', ''))
if name.include? '='
@attributes[name.sub('=', '').to_sym] = Populator.interpret_value(args.first)
else
@attributes[sym]
end
else
super
end
end
end
end
6 changes: 3 additions & 3 deletions script/profiler
Expand Up @@ -30,7 +30,7 @@ begin
printer_class = RubyProf::FlatPrinter
end
printer = printer_class.new(results)
printer.print($stderr, 0)
printer.print($stdout)
rescue LoadError
require "prof"
$stderr.puts 'Using the old ruby-prof extension.'
Expand All @@ -39,13 +39,13 @@ begin
profile_me
results = Prof.stop
require 'rubyprof_ext'
Prof.print_profile(results, $stderr)
Prof.print_profile(results, $stdout)
end
rescue LoadError
require 'profiler'
$stderr.puts 'Using the standard Ruby profiler.'
Profiler__.start_profile
profile_me
Profiler__.stop_profile
Profiler__.print_profile($stderr)
Profiler__.print_profile($stdout)
end

0 comments on commit 1c10123

Please sign in to comment.