Shedrack Sunday
Shedrack Sunday

Reputation: 11

Is it possible to use a module method in a standalone function in Ruby?

i have a JSON FILE with some data, a module that conatains two methods to load a music and genre. in the same directory, i have class file that has classes for Music and Gener. i want to be able to call the classes in a main.rb file, then creating function that will load my module method, without using a class based setting. my question is, is it possible to add the include <moduleName> syntax without using classes?

Music.rb

require_relative '../item'

class MusicAlbum < Item
  attr_accessor :on_spotify, :name, :publish_date

  def initialize(name, publish_date, on_spotify)
    @id = Random.rand(1..100)
    super(publish_date) # Music calls all constructor item with super
    @name = name
    @on_spotify = on_spotify
  end

  def can_be_archived?
    super && @on_spotify
  end
end

./modules/music_module.rb

require 'json'
require_relative '../classes/music_album'

module MusicAlbumModule
  def load_music_albums
    data = []
    file = './json_files/music_album.json'
    if File.exist?(file)
      JSON.parse(File.read(file)).each do |music|
        data.push(MusicAlbum.new(music['name'], music['publish_date'], music['on_spotify']))
      end
    else
      File.write('./json_files/music_album.json', [])
    end

    data
  end

  def create_music_album
    data = []
    @music_albums.each do |album|
      data.push({ name: album.name, publish_date: album.publish_date, on_spotify: album.on_spotify })
    end
    File.write('./json_files/music_album.json', JSON.generate(data))
  end
end

In a class based case, i'll use the module while creating a new function like this

def add_music_album
  puts 'Album name: '
  name = gets.chomp

  puts 'Date of publish [Enter date in format (yyyy-mm-dd)]'
  publish_date = gets.chomp

  puts 'Is it available on Spotify? Y/N'
  on_spotify = gets.chomp.downcase
  case on_spotify
  when 'y'
    @music_albums.push(MusicAlbum.new(name, publish_date, true))
  when 'n'
    @music_albums.push(MusicAlbum.new(name, publish_date, false))
  end
  puts 'Music album created'
end

So how is it possible to use a module method inside of a class

It works with a class, where i used include the module with the include key word inside my class and get acces to the methods. but am not able to do it without the class

Upvotes: 0

Views: 158

Answers (1)

Aria
Aria

Reputation: 104

You can call module functions without including the module in a class. To do that, you need to declare the methods of your module with the self prefix.

Example:

my_module.rb

module MyModule
  def self.my_module_method
    # do something
  end
end

random_script.rb

require_relative 'my_module'

def random_function
  MyModule.my_module_method
end

Upvotes: 2

Related Questions