Using 'relative_require' to separate functions, classes, instantiation
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!
Published on 24 Dec 2016
by Alexander Garber
all tags
100daysofcode activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career ci-cd cli cloud code coding config configuration cp crud cryptography css csv database db demo design devops django docker email erp feelsgood filter fugitive gif gist git gmail gnome gnome pomodoro grep hebrew http ide isbn-fetcher iso javascript job search js kanban kindle koans learning linkedin linux logger manjaro map markdown microservices mobi mtp neovim nodejs nvchad packages panda pastbin patch portfolio post postgres pytest python rails reduce refactoring reflections rest routes rspec ruby salesforce script scripting security sed shell sql string_replacement study tasks tdd terminal testing tmux ttd version_control vim vim sort walkthrough webdev workflow zsh