Rails全局函数:调用传递对象函数

时间:2017-07-18 22:40:12

标签: ruby-on-rails

我想创建一个全局函数,我将把它放在我的应用程序控制器中。

为了使这个问题变得简单,以下是我要做的一个例子:

在我的library(data.table) library(plyr) DT <- fread('unique_point biased data_points team groupID up1 FALSE 3 A xy28352 up1 TRUE 4 A xy28352 up2 FALSE 1 A xy28352 up2 TRUE 0 X xy28352 up3 FALSE 12 Y xy28352 up3 TRUE 35 Z xy28352') ldply(LETTERS, function(x){ n <- nrow(DT[team == as.character(x),]) DT[, as.character(x) := n] return(DT[team == x,]) }) > DT unique_point biased data_points team groupID A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 1: up1 FALSE 3 A xy28352 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 2: up1 TRUE 4 A xy28352 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 3: up2 FALSE 1 A xy28352 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 4: up2 TRUE 0 X xy28352 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 5: up3 FALSE 12 Y xy28352 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 6: up3 TRUE 35 Z xy28352 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1

/application_controller.rb

在我正在工作的控制器中:

def self.global_function(device)
    p device
end

这是有效的,但我想让它工作,例如,def some_function global_function(Device.find(some_id)) end 方法。最终结果将允许我这样调用:

.last

仍然传递设备对象,但不需要参数。

除了审美之外,我无法说明为什么我更喜欢一个而不是另一个。如果使用一种方式而不是另一种方式存在任何缺点,我也想知道这一点。感谢

1 个答案:

答案 0 :(得分:1)

您对什么是功能与什么是方法感到困惑。

这与制作&#34;全局功能&#34;无关。您只需要在Device上定义一个普通的旧方法:

class Device < ActiveRecord::Base
  def some_method
    # do something with `self`
  end
end

这将允许您在任何global_method实例上调用Device,例如find返回的实例:

Device.find(some_id).some_method