Prev | Current Page 267 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

We can use the column_names array that Active Record supplies
and define a function for every column. This method will perform the same actions as the
method_missing we used before, but instead of being called implicitly (as method_missing
does), they will be called explicitly. This will remove any ambiguity and let us be sure our
methods refer to columns in the database.
However, we??™ll need to rearrange our conditions class a little, for example:
module RQuery
class Conditions
def initialize(active_record, &blk)
@active_record = active_record
@columns = []
define_column_methods
blk.call(self) unless blk.nil?
end
def define_column_methods
active_record = @active_record
(class << self; self; end).class_eval do
active_record.column_names.each do |column|
define_method(column) do
column = Column.new(column_name)
@columns << column
column
end
end
end
end
def method_missing(name, *args)
raise "The column #{name} was not found on #{@active_record.class.name}"
end
end
end
The define_column_methods method is where our new work is getting done.


Pages:
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279