简体   繁体   中英

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.

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?

Do I make it a gem?

Thanks.

Making it a gem and installing it is one option. 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:

export RUBYLIB=path_to_the_directory_where_the_file_is

Then, require that file and use it. 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:

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. It's trivial to call them using back ticks or %x , or chain them using regular pipes ( | ) as we would a regular app.

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.

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.

Just because they're written in Ruby doesn't mean they have to be a gem or module. Ruby is capable of much more than that and fits into the usual host ecology well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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