Using 'relative_require' to separate functions, classes, instantiation
Published on 24 Dec 2016
by Alexander Garber
My goal is to create a main.rb file that does nothing but instantiate the classes and execute their methods. As you can see below, this is possible, at least in a simple application,
but is this good practice?
It feels neater to separate classes, functions, etc; but then again, this might be akin to separating vocabulary sheets by parts of speech -- tidy, but impracticable.
It might be better practice to group blocks of code that work on the same portion of the program. Please let me know what works in your experience.
A simple function:
A class that uses this function as a method:
Finally, an instance of the class that executes its method:
Output:
It feels neater to separate classes, functions, etc; but then again, this might be akin to separating vocabulary sheets by parts of speech -- tidy, but impracticable.
It might be better practice to group blocks of code that work on the same portion of the program. Please let me know what works in your experience.
A simple function:
## demo_function.rb
def hello_world()
puts "Hello world!"
end
A class that uses this function as a method:
## demo_class.rb
require_relative 'demo_function.rb'
class Demo
def enter()
hello_world()
end
end
Finally, an instance of the class that executes its method:
## demo_main.rb
require_relative 'demo_class'
a_class = Demo.new()
a_class.enter()
Output:
Hello World!
all tags
activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career cli cloud code coding config configuration cp crud css database db design devops django email erp filter fugitive gif gist git gnome grep hebrew http ide isbn-fetcher iso javascript job search js kanban kanban\ kindle koans linux logger manjaro map markdown microservices mobi mtp neovim nodejs packages pastbin patch post python rails reduce refactoring rest routes rspec ruby scripting security sed shell sql string_replacement study tdd terminal testing version_control vim walkthrough workflow