Skip to content

Instantly share code, notes, and snippets.

@NateBarnes
Created August 20, 2011 03:59
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 NateBarnes/1158636 to your computer and use it in GitHub Desktop.
Save NateBarnes/1158636 to your computer and use it in GitHub Desktop.
Example options methods for polymorphic options model
module ActiveRecordAddons
def has_options
class_eval do
has_many :raw_options, :as => :owner, :class_name => "Option"
def options
opts = {}
raw_options.each { |opt| opts[opt.key.to_sym] = converter(opt.value) }
opts
end
def add_options opts
opts.map do |key, value|
raw_options.create! :key => key, :value => value
end
end
def options= opts
raw_options.each { |opt| opt.destroy }
add_options opts
end
private
def converter val
Integer(val)
rescue ArgumentError
Float(val)
rescue ArgumentError
val
end
end
end
end
ActiveRecord::Base.extend ActiveRecordAddons
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment