而不是像这样在类中定义范围:
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
。 如何在用户模型上执行first_added
中定义的阻止?
我如何通常在课堂上调用一个块? 谢谢
答案 0 :(得分:1)
如果我正确理解您的问题,您可以使用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
答案 1 :(得分:0)
这不是你想要的,但也许这会有所帮助
我不确定是否可以调用proc on 。我认为只能使用来调用proc ,i.t。在您的情况下,将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
答案 2 :(得分:0)
以下三种使用first
从User
致电Manager
的方法:
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
档案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