Skip to content

Instantly share code, notes, and snippets.

@sbellware
Created May 31, 2010 01:13
Show Gist options
  • Save sbellware/419451 to your computer and use it in GitHub Desktop.
Save sbellware/419451 to your computer and use it in GitHub Desktop.
ActiveRecord model without a backing table. Useful for View Models, and other plain old objects with validations, and other ActiveRecord facilities like associations, etc.
module ViewModel
def self.included(base)
base.extend ClassMethods
base.class_inheritable_accessor :columns
base.columns = []
end
module ClassMethods
def column(name, sql_type = :text, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end
end
def save(validate = true)
validate ? valid? : true
end
end
# example
class Foo < ActiveRecord::Base
include ViewModel
column :bar
column :blah
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment