Created
November 24, 2008 10:33
-
-
Save tomafro/28440 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ColumnReader | |
def column_reader(column_name, options = {}) | |
name = options.delete(:as) || column_name.to_s.pluralize | |
behaviour_module = column_reader_module(column_name) | |
column = columns_hash[column_name.to_s] | |
behaviour_module.module_eval %{ | |
def #{name}(options = {}) | |
connection.select_all(construct_finder_sql(options.merge(:select => '#{column_name}'))).collect do |value| | |
v = value.values.first | |
#{column.type_cast_code('v')} | |
end | |
end | |
} | |
extend behaviour_module | |
end | |
private | |
def column_reader_module(column_name) | |
module_name = "Raw#{column_name.to_s.camelize}Access" | |
if constants.include?(module_name) | |
const_get(module_name) | |
else | |
const_set(module_name, Module.new) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ActiveRecord::Base.extend ColumnReader | |
class Animal < ActiveRecord::Base | |
column_reader 'id' | |
column_reader 'name' | |
named_scope :dangerous, :conditions => {:carnivorous => true} | |
end | |
Animal.names | |
#=> ['Lion', 'Tiger', 'Zebra', 'Gazelle'] | |
Animal.names :limit => 1 | |
#=> ['Lion'] (Normal finder options supported) | |
Animal.dangerous.names | |
#=> ['Lion', 'Tiger'] (Scoping respected) | |
Animal.ids | |
#=> [1, 2, 3] (Values cast correctly) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment