Skip to content

Instantly share code, notes, and snippets.

@tomafro
Created November 24, 2008 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomafro/28440 to your computer and use it in GitHub Desktop.
Save tomafro/28440 to your computer and use it in GitHub Desktop.
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
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