【问题标题】:passing a method with parameters as an argument in ruby [duplicate]在ruby中传递带有参数的方法作为参数[重复]
【发布时间】:2018-07-17 03:36:11
【问题描述】:

我目前需要传递一些方法作为参数才能正确渲染json:

render json: @objects.to_json(methods: [:num_of_properties])

此语法当前有效。但是,我想通过另一种方法;此方法接受 1 个参数。

我认为这会起作用:

render json: @objects.to_json(methods: [:num_of_properties, :property_is_owned_by?(current_user)])

不起作用。这甚至可能吗?我认为,如果您首先可以将方法作为参数传递,那么您必须能够传递接受参数的方法。但我不知道。我对 Ruby 不太熟悉。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    从技术上讲,它不打算给参数 to_json 只接受 getter。但你可以按照这些思路做一些事情:

    class ObjectClassOfYourChoice
      attr_accessor :current_user
    
      def property_is_owned_by?(user = nil)
        user ||= current_user
        # rest of your code
      end
    end
    
    
    @objects.each do |object|
      object.current_user = current_user
    end
    render json: @objects.to_json(methods: [:property_is_owned_by?]
    

    虽然我不会这样做,因为您必须为所有对象设置,而这只是代码味道。

    【讨论】:

    • 完美运行,谢谢!
    • 感谢 @engineersmnky 提醒我方法参数中的错字并指控我复制答案。我将课程重命名为更合适的方式,因为任何阅读此内容的人都看不到我调用的是 Object,因为 OP 调用了他的 var @objects
    猜你喜欢
    • 2014-04-09
    • 2014-04-22
    • 2010-10-06
    • 2015-05-11
    • 2011-04-30
    • 2013-09-13
    • 2013-08-10
    • 2016-11-02
    • 2015-03-04
    相关资源
    最近更新 更多