如何打电话或激活课程?

时间:2012-04-24 18:24:44

标签: ruby

在我的lib文件夹中,我有billede.rb:

class Billede
  require 'RMagick'
  #some code that creates a watermark for a image
  image.write(out)
end

如何拨打/激活课程?是将其更改为Rake任务的唯一方法吗?

3 个答案:

答案 0 :(得分:5)

您无法直接致电课程。你必须在该类上调用一个方法。例如:

class Billede
  def self.foobar
    # some kind of code here...
  end
end

然后你可以通过Billede.foobar

来调用它

在尝试执行更复杂的操作(例如使用Rmagick操作图像)之前,您可能应该阅读一些关于基本ruby语法的文档。

答案 1 :(得分:2)

代码'在类中“运行就像任何其他代码一样。如果您有这样的Ruby文件:

puts "Hello from #{self}"
class Foo
  puts "Hello from #{self}"
end

然后运行该文件(通过命令行上的ruby foo.rb或脚本中的require "./foo"load "foo.rb")然后您将看到输出:

  

你好主要   来自Foo的你好

如果要加载一个“做某事”的实用程序,然后可以从IRL或Rails控制台等REPL调用,那么执行以下操作:

module MyStuff
  def self.do_it
    # your code here
  end
end

您可以require "./mystuff"加载代码,当您准备好运行代码时,请输入MyStuff.do_it

而且,正如您可能猜到的,您还可以创建接受参数的方法。

如果你想定义一个可以包含在其他文件中的文件(没有直接的副作用),但是只要文件自己运行它也会“做它的事”,你可以这样做:

module MyStuff
  def self.run!
    # Go
  end
end

MyStuff.run! if __FILE__==$0

现在,如果您requireload此文件将不会调用run!方法,但如果您从命令行键入ruby mystuff.rb它将会。

答案 2 :(得分:1)

# in /lib/billede.rb
class Billede

  def self.do_something(arg)
    # ...
  end

  def do_anotherthing(arg)
    # ...
  end

end

# inside a model or controller
require 'billede'

Billede::do_something("arg")
# or
billede_instance = Billede.new
billede_instance.do_anotherthing("arg")