Module: Her::Model::ORM::ClassMethods

Defined in:
lib/her_extension/model/orm.rb

Instance Method Summary collapse

Instance Method Details

#scope(name, code) ⇒ Object

Create a new chainable scope

Examples:

class User
  include Her::Model

  scope :admins, lambda { where(:admin => 1) }
  scope :page, lambda { |page| where(:page => page) }
enc

User.admins # Called via GET "/users?admin=1"
User.page(2).all # Called via GET "/users?page=2"


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/her_extension/model/orm.rb', line 32

def scope(name, code)
  
  # Add the scope method to the class
  metaclass = (class << self; self end)
  metaclass.send(:define_method, name) do |*args|
    instance_exec(*args, &code)
  end
  Relation.scopes["#{self.to_s}.#{name}"] = code
  
  # Add the scope method to the Relation class
  Relation.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    def #{name}(*args)
      parent_klass = @parent.instance_variable_get("@klass") || @parent.to_s
      instance_exec(*args,&self.class.scopes["\#{parent_klass}.#{name}"])
    end
  RUBY
end