如何在控制器(RoR)中调用方法?

时间:2013-08-14 07:22:34

标签: ruby-on-rails csv

我是RoR的新手,我玩过源代码。但我有一个问题,我已经建立了'def A'用于创建第一个CSV文件,'def B'用于创建第二个CSV文件。每个'def'都有自己的按钮,但我有第三个按钮来创建所有CSV(从第一个和第二个CSV文件生成输出。)

可能的方法是什么?

def first_csv
...
end

def second_csv
..
end

def all_csv
<< how to call get first and second csv >>
end

提前致谢,

2 个答案:

答案 0 :(得分:2)

它应该像你想象的一样简单:

def all_csv
  first_csv
  second_csv
end

答案 1 :(得分:2)

Muntasim的回答是正确的,但我必须添加一些额外的信息。

Ruby提供了两种类型的方法..类方法和实例方法。

class MyClass < AvtiveRecord::Base

  # class method
  def self.foo
    # do something
    # within this scope the keyword "self" belongs to the class
  end

  # another class method which calls internally the first one
  def self.bar
    something = foo # self.foo could also be written
    # do something with something
    # within this scope the keyword "self" belongs to the class
  end

  # instance method
  def foo
    # do something
    # if you use the keyword "self" within an instance method, it belongs to the instance
  end

  # another instance method which calls class and the first instance method
  def bar
    mystuff = Myclass.bar # if you want to call the class method you cannot use "self", you must directly call the class
    mystuff2 = foo # self.foo is the same, because of the instance scope
    return [mystuff, mystuff2]
  end

end

您可以调用最后一个实例方法,如下面的

instance = MyClass.first
instance.bar