不像这样在类中定义作用域:
scope :first_user, -> { first }
这样命名:User.first_user
我想在另一个类中定义一个块,它可以在用户类中调用,并像Scope一样工作:
这段代码不工作,但它应该表明我想要实现的行为:
class Manage
def get_first_user
User.&first_added
end
def first_added
Proc.new { first }
end
end
当我运行这段代码时:
a = Manage.new
a.get_first_user
上面写着我,& undefined method for User
。如何在User模型上执行first_added
中定义的Block ?
通常如何在类上调用块?谢谢
如果我正确理解了您的问题,您可以使用class_eval
:
>> foo = Proc.new { count }
=> #<Proc:0x007f1aa7cacfd8@(pry):30>
>> Buyer.class_eval(&foo)
(30.6ms) SELECT COUNT(*) FROM "buyers"
=> 1234
或者用你的例子:
class Manage
def get_first_user
User.class_eval(&first_added)
end
def first_added
Proc.new { first }
end
end
这不是你想要的,但可能会有帮助。
我不确定是否可以在上调用进程。我认为一个人只能用来调用proc ,比如在你的情况下传递User
作为参数。
def get_first_user
wrap User, &first_added
end
def first_added
Proc.new { |model| model.where(...) }
end
private
def wrap(model, &block)
yield model
end
从Manager
调用User
上的first
有三种方法:
-
Object#send
:http://ruby-doc.org/core-2.3.1/Object.html method-i-send -
Module#class_eval
:http://ruby-doc.org/core-2.3.1/Module.html method-i-class_eval
File manage.rb
:
class User
def self.first
puts 'record would probably go here'
end
def self.yielder
print "via yielder => "
self.send(yield) if block_given?
end
def self.blocker(&block)
print "via blocker => "
self.send(block.call) if block_given?
end
def self.evaller(&block)
print "via evaller => "
self.class_eval(block.call) if block_given?
end
end
class Manage
def get_first_user
User.yielder(&first_added)
User.blocker(&first_added)
User.evaller(&first_added)
end
def first_added
Proc.new {"first"}
end
end
a = Manage.new
a.get_first_user
输出:$ ruby manage.rb
via yielder => record would probably go here
via blocker => record would probably go here
via evaller => record would probably go here