Skip to content

Instantly share code, notes, and snippets.

@anolson
Created December 21, 2010 20:02
Show Gist options
  • Save anolson/750484 to your computer and use it in GitHub Desktop.
Save anolson/750484 to your computer and use it in GitHub Desktop.
ActiveRecord like model with validations and dynamic attributes
require 'rubygems'
require 'active_model'
require 'active_support'
class Model
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
def initialize(attributes = {})
attributes.each { |name, value|
create_attr(name, value)
}
end
def persisted?
false
end
def create_attr(name, value)
self.class.class_eval { attr_accessor name.to_sym }
if(value.instance_of?(Array))
send "#{name}=", value.collect { |v| class_for(name).new(v) }
else
send "#{name}=", value
end
end
private
def method_missing(method_name, *args, &block)
match = method_name.to_s.match(/(.*?)([?]?)$/)
case match[2]
when "?"
instance_variable_defined?("@#{match[1]}")
end
end
def class_for(key)
Object.const_get(key.to_s.classify)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment