简体   繁体   English

如何将独立维护的 ruby​​ 脚本合并到 Rails 应用程序中

[英]How do I incorporate an independently maintained ruby script into a rails application

I have a ruby script (.rb) that opens a file and makes a csv file after some parsing.我有一个 ruby​​ 脚本 (.rb),它打开一个文件并在一些解析后制作一个 csv 文件。

I maintain the script independently and may use in other applications.我独立维护脚本,可能会在其他应用程序中使用。

Right now I just copied and pasted the code into my controller... I know that isn't right!现在我只是将代码复制并粘贴到我的控制器中......我知道这是不对的!

How am I supposed to incorporate this ruby script to my application?我应该如何将这个 ruby​​ 脚本合并到我的应用程序中?

Do I make it a gem?我让它成为宝石吗?

Thanks.谢谢。

Making it a gem and installing it is one option.使其成为 gem 并安装它是一种选择。 Otherwise, register the directory of the file as load path.否则,将文件的目录注册为加载路径。 That part may depend on the operating system.该部分可能取决于操作系统。 For example, with Ubuntu Linux, I do in the terminal:例如,对于 Ubuntu Linux,我在终端中执行:

export RUBYLIB=path_to_the_directory_where_the_file_is

Then, require that file and use it.然后, require该文件并使用它。 When you want your library to behave differently depending on if it was called directly from the command or from another ruby script, the common way is to write in your library:当您希望库根据是直接从命令调用还是从另一个 ruby​​ 脚本调用而有不同的行为时,常用的方法是在库中编写:

if __FILE__ == $0
  commands_to_execute_when_called_directly_from_command
end

We write little Ruby-based command-line tools all the time, and treat them as regular Linux apps.我们一直在编写基于 Ruby 的小型命令行工具,并将它们视为常规的 Linux 应用程序。 It's trivial to call them using back ticks or %x , or chain them using regular pipes ( | ) as we would a regular app.使用反引号或%x调用它们,或者像使用常规应用程序一样使用常规管道 ( | ) 链接它们是微不足道的。

If we're going to be throwing a lot of data around, often we'll add a --json flag using OptionParser, which lets us emit JSON to the calling program, making it easier to reuse the data instead of having to parse CSV or columnar data.如果我们要抛出大量数据,通常我们会使用 OptionParser 添加一个--json标志,它允许我们向调用程序发出 JSON,从而更容易重用数据,而不必解析 CSV或列数据。

You can install those sort of apps in /usr/local/bin on a *nix system, make sure the path is set to search there, and then share the code among shell, Ruby or any other language capable of using a sub-shell.您可以在 *nix 系统上的/usr/local/bin安装此类应用程序,确保将路径设置为在那里搜索,然后在 shell、Ruby 或任何其他能够使用子 shell 的语言之间共享代码.

Just because they're written in Ruby doesn't mean they have to be a gem or module.仅仅因为它们是用 Ruby 编写的,并不意味着它们必须是 gem 或模块。 Ruby is capable of much more than that and fits into the usual host ecology well. Ruby 的能力远不止这些,并且非常适合通常的宿主生态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM