在模型上调用块

时间:2016-07-02 20:30:56

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

而不是像这样在类中定义范围:

 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中定义的阻止?

我如何通常在课堂上调用一个块? 谢谢

3 个答案:

答案 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)

以下三种使用firstUser致电Manager的方法:

档案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