How to automatically call classes in Ruby script from a specific directory - ruby

I have a directory /lib where I store *.rb files. Each one of them contains a class with a single class method remove_user().
How can I make the main script automatically go over those files and call the same method on all of them? I want to just drop-in files in that directory in the future without modifying the main script in any way.
I do know how to require all the files from a directory based on "Best way to require all files from a directory in ruby?", but I'm not very sure how to invoke the classes "in a loop" from here.
Update
I've tried a the code suggested in "How do I create automatically a instance of every class in a directory?"
files = Dir.glob("lib/*.rb")
def load_modules(class_files)
puts class_files
before = ObjectSpace.each_object(Class).to_a
class_files.each {|file| require_relative file }
after = ObjectSpace.each_object(Class).to_a
(after - before).each {|klass| klass.new.delete_user('myemail#mail.com', 'Audit', 'Test')}
load_modules(files)
end
It produces an error:
/Users/apinchuk/RubymineProjects/autoaudit/init.rb:16:in `new': can't create instance of singleton class (TypeError)
from /Users/RubymineProjects/autoaudit/init.rb:16:in `block in load_modules'
from /Users/RubymineProjects/autoaudit/init.rb:16:in `each'
from /Users/RubymineProjects/autoaudit/init.rb:16:in `load_modules'
from /Users/RubymineProjects/autoaudit/init.rb:20:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
And there is nothing I could find about this error.
The create_uat_robot.rb has a structure like this:
class CreateUatRobot
def self.delete_user(email, first_name, last_name)
...
end
end
The name of the file is create_uat_robot.rb
Trying #moveson suggestion as follows:
files = Dir.glob("lib/*.rb")
files.each {|file| require_relative file }
klasses = Dir["lib/*.rb"].map {|file| File.basename(file, '.rb').camelize.constantize}
klasses.each { |klass| klass.delete_user(arguments) }
worked for me.

First you need to create an array of class names:
>> klasses = Dir["lib/*.rb"].map {|file| File.basename(file, '.rb').camelize.constantize }
Then you can call your method on each of them in turn:
>> klasses.each { |klass| klass.remove_user }
If you are not using Rails, you can require ActiveSupport's String extension methods (require 'active_support/core_ext/string'), which will give you the camelize and constantize methods.

Related

NameError: uninitialized constant error

Given the following code:
module Backup
module Destination
class Base
def initialize
puts 'Base'
end
end
end
end
module Backup
module Destination
class Test < Base
def initialize
puts 'Test'
super
end
end
end
end
Backup::Destination::Test.new
This works as expected, outputting:
Test
Base
However if I split things up like this:
# lib/backup.rb
require_relative 'backup/destination/base'
module Backup; end
# lib/backup/destination/base.rb
require_relative 'test'
module Backup
module Destination
class Base
def initialize
puts 'Base'
end
end
end
end
# lib/backup/destination/test.rb
module Backup
module Destination
class Test < Base
def initialize
puts 'Test'
super
end
end
end
end
And execute with the following (from irb):
require_relative 'lib/backup'
I get this error:
NameError: uninitialized constant Backup::Destination::Base
from /lib/backup/destination/test.rb:3:in `<module:Destination>'
from /lib/backup/destination/test.rb:2:in `<module:Backup>'
from /lib/backup/destination/test.rb:1:in `<top (required)>'
from /lib/backup/destination/base.rb:1:in `require_relative'
from /lib/backup/destination/base.rb:1:in `<top (required)>'
from /lib/backup.rb:1:in `require_relative'
from /lib/backup.rb:1:in `<top (required)>'
from (irb):1:in `require_relative'
What am I missing?
Note: I couldn't post the above without adding more details. Stupid feature because in this case code is worth a thousand words. (this text allowed the question to be posted)
The problem is that you are requiring test.rb before your Base class is defined. One possible solution is to move your require to the bottom of base.rb.
Another possible solution is to remove your require from base and require both files in the correct order from backup.
Made the following changes to fix the problem:
# lib/backup.rb
require_relative 'backup/destination/base'
require_relative 'backup/destination/test'
module Backup; end
And removed the require_relative statement from lib/backup/destination/base.rb. This fixed the order of the require_relative statements. I mistakenly thought the files were required before anything was executed.

Can't understand why I'm getting a `initialize': uninitialized constant Controller::View (NameError)

I'm trying to understand why I'm getting this error and I suspect it's because I have my Controller class and View class in two separate Ruby files. I was told that using require_relative 'filename' should reference all the code from one file into another, but I seem to be missing something. Okay here goes,
In controller.rb file, I have
require_relative 'view'
require_relative 'deck_model'
require_relative 'flashcard_model'
class Controller
def initialize
#deckofcards = Deck.new
#welcome = View.new.welcome
#player_guess = View.new.get_user_guess
#success_view = View.new.success
#failure_view = View.new.failure
end
def run
#Logic to run the game
# #current_card
# #user_guess
puts "Let's see if this prints"
# pull_card_from_deck
end
end
In my view.rb file, I have,
require_relative 'controller'
class View
attr_accessor :userguess
def initialize (userguess = " ")
#userguess = userguess
end
def welcome
system ("clear")
puts "Welcome! Let's play a game."
puts "I'll give you a definition and you have to give me the term"
puts "Ready..."
end
def get_user_guess
#userguess = gets.chomp.downcase
end
def success
puts "Excellent! You got it."
end
def failure
puts "No, that's not quite right."
end
end
However when I run controller.rb, I get the following error,
/Users/sean/Projects/flash/source/controller.rb:11:in `initialize': uninitialized constant Controller::View (NameError)
from /Users/sean/Projects/flash/source/controller.rb:51:in `new'
from /Users/sean/Projects/flash/source/controller.rb:51:in `<top (required)>'
from /Users/sean/Projects/flash/source/view.rb:1:in `require_relative'
from /Users/sean/Projects/flash/source/view.rb:1:in `<top (required)>'
from controller.rb:1:in `require_relative'
from controller.rb:1:in `<main>'
Can anyone please help me figure this out.
You did not post your full code, but it sounds like this is an error caused by the circular dependencies you specified in your project. You have view.rb depending on controller.rb and controller.rb depending on view.rb. The Ruby interpreter will not execute these files simultaneously; it has to execute one and then execute the other.
It looks like it is executing controller.rb first, but it sees that view.rb is required, so it starts executing that. Then in view.rb it sees that controller.rb is required, so it starts executing controller.rb again. Then at some point in controller.rb, you must be creating a new instance of the Controller class. But we aren't done defining the View class yet, so View is undefined and you get an exception while trying to create that controller.
To fix this, you should consider not creating any Controller or View objects until both of the classes are fully loaded.
+1 to #DavidGrayson comment.
If my assumption is correct, your issue is with require_relative 'controller' in your view.rb file.
If you see, it looks like View is requiring Controller then Controller gets loaded which seems to be sending new somewhere to Controller which then sends new to View but it hasn't been completely required.

Rails 4: Undefined method on module

I have a module in app/misc/dsl/builder.rb that has this code
module Dsl
class Builder
def initialize(context, &block)
return if not block_given?
parent_context = block.binding.eval "self"
parent_context.extend Proxy
parent_context.object = context
parent_context.instance_eval &block
end
end
def self.set_context(context, &block)
Dsl::Builder.new(context, &block)
end
end
Note: this directory misc is preloaded in application.rb
config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**/}'),
Rails.root.join('app', 'misc', '{**/}')
]
Then, somewhere in the text (lets say at foo.rb) I have this code:
Dsl.set_context(obj) do
#some code with obj receiving messages
end
The test stack we are using consists on Zeus+Guard+Rspec. Now, lets say I rewrite the code to something not working
Dsl.set_context(obj) do
asdqwe #this message does not exists
end
From times to times, I receive this baffling message
1) SomeOtherClass search_hash receiving keywords params should query for those keywords
Failure/Error: subject.search_hash
NoMethodError:
undefined method `set_context' for Dsl:Module
# ./app/misc/product_query.rb:116:in `base_search_hash'
# ./app/misc/product_query.rb:25:in `search_hash'
# ./spec/misc/product_query_spec.rb:78:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
instead of the correct message that should be regarding undefined method asdqwe
Any clue about this?
Look here
it says:
Rails 3 has been updated such that classes/modules (henceforth, C/M)
are lazy loaded from the autoload paths as they are needed
so, you can do require_relative 'app/misc/dsl/builder.rb' in your rspec_helper.rb (can it be better with just require?) The problem must be that the loader doesn't know in advance where to find Dsl.set_context, but he will know once you have referenced Dsl::Builder
Hope it helps

Cannot load data file in Sinatra

I created the following parser:
require "./artist"
require "./song"
require "./genre"
require "debugger"
class Parser
attr_accessor :artists, :genres, :song
attr_reader :mp3
REGEX = /(?<artist>.*)\s\-\s(?<song>.*)\s\[(?<genre>.*)\]/
def initialize(directory="data")
debugger
#mp3 = Dir.entries(directory).select {|f| !File.directory? f}
debugger
end
def parse
#mp3.map do |file|
match = REGEX.match(file)
artist = Artist.find_by_name(match[:artist]) || Artist.new.tap {|artist| artist.name = match[:artist]}
song = Song.new
song.name = match[:song]
song.genre = Genre.find_by_name(match[:genre]) || Genre.new.tap {|genre| genre.name = match[:genre]}
#debugger
artist.add_song(song)
end
end
end
a = Parser.new.parse
I tried running it by calling parser.rb in the directory, lib, where it is located. I get the following error messages:
Parser.rb:47:in `open': No such file or directory - data (Errno::ENOENT)
from parser.rb:47:in `entries'
from parser.rb:47:in `initialize'
from parser.rb:68:in `new'
from parser.rb:68:in `<main>'
This is my file structure:
Can anyone please tell me why it cannot recognize my data directory? I have been staring for a while now and cannot figure it out. It was working like 10 mins ago and I cannot remember what I change to get it all messed up.
Appreciate your feedback! Thanks
You should be able to run your example like ruby -I/lib lib/parser.rb from the directory above lib. The -I will set the "include path", such that the ruby interpreter will find the other required ruby files like (lib/)song.rb.

Can't call ruby module method

cat module1.rb =>
module Module1
def add(a,b)
return a+b
end
def subtract(a,b)
return a-b
end
end
cat call.rb =>
#!/home/user1/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
include './Module1.rb
temp = add(5,2)
print temp
print "\n"
ruby call.rb =>
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- Module1 (LoadError)
from <internal:lib/rubygems/custom_require>:29:in `require'
from call.rb:3:in `<main>'
Can anyone fix it ?
Place two files in the same directory. Call the first one module1.rb and make it look exactly like this:
module Module1
def add(a, b)
return a + b
end
def subtract(a, b)
return a - b
end
end
Call the second one call.rb and make it look exactly like this
require './module1.rb'
include Module1
temp = add(5,2)
print temp
print "\n"
At the commandline, run ruby call.rb. You should see an output of 7.
I assume you're using Ruby 1.9?
Then try
require_relative 'module1'
include Module1
temp = add(5,2)
puts temp
That should do it.
require loads a file from Ruby's $LOAD_PATH. If you want to load a file relative to the current file, then you need to use require_relative instead.
You should require the file before including.
require 'module1.rb'
include Module1
And make sure the two file are in same directory.

Resources