Skip to content

Instantly share code, notes, and snippets.

@DimaD
Created April 27, 2009 09:02
Show Gist options
  • Save DimaD/102401 to your computer and use it in GitHub Desktop.
Save DimaD/102401 to your computer and use it in GitHub Desktop.
I want to write acts_as List instead of acts_as_list. Also it help to abstract self.included idiom
module ActsAs
end
class ActiveRecord::Base
def self.const_missing name
if ActsAs.const_defined?(name)
ActsAs.const_get(name.to_s)
else
raise NameError.new("uninitialized constant #{name}", name)
end
end
def self.acts_as const, *options, &block
extend(const.const_get('ClassMethods')) if const.const_defined?('ClassMethods')
include const.const_get('InstanceMethods') if const.const_defined?('InstanceMethods')
const.send(:setup, self, *options, &block) if const.respond_to?(:setup)
end
end
module ActsAs
module List
def self.setup cl, options={}, &block
cl.class_eval <<-EOV
def default_position
#{options[:default_position]}
end
EOV
end
module ClassMethods
def acts_as_list_class
"::#{self.name}"
end
end
module InstanceMethods
def insert_at number
@position = number
end
end
end
end
class TodoItem < ActiveRecord::Base
belongs_to :todo_list
acts_as List, :scope => :todo_list
end
class TodoList < ActiveRecord::Base
has_many :todo_items, :order => "position"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment