What are the best methods for reusing code between different Ruby projects?

guys!

I am a software developer with a Java background and I am launching some projects using the Ruby web infrastructure (Padrino / Sinatra).

In my java projects, I usually had some β€œcommon” projects whose classes were used in several projects. For example, I had a central authentication service and a common database that stored user profiles. All of my projects that used this service shared some models mapped to the user profile database.

So, despite the structure, orm lib, etc., what's the best way to exchange codes across multiple Ruby projects?

+6
source share
2 answers

In addition, ruby stones are one of the best ways to reuse common parts of the code. Gems have names, version numbers, and descriptions, so you can easily maintain updated versions of these libraries, install and uninstall, manage local computer settings using the gem command, available from the command line. Gems have become standard with Ruby 1.9, but before you have to use the require 'rubygems' in your scripts. There are several tools that help you create them, such as bundler . Bundler is not only a tool for creating gems, but also an excellent application dependency manager.

+4
source

Put your code in something.rb and require at the top of your other script (s).

You can also use load instead of require , but require has a nice property that will not contain the file more than once. In addition, using load requires a .rb extension, whereas require does not matter, i.e.

 #some_script.rb puts('hello world') #another script require 'some_script' >> hello world load 'some_script' LoadError: no such file to load -- some_script from (irb):2:in 'load' from (irb):2 

You will almost always use require , but load also an option if you want to use it for any reason.

0
source

Source: https://habr.com/ru/post/902860/


All Articles