How to Access Ruby Method Inside Module and Inside a Class from Another .Rb File

How to access Ruby method inside module and inside a class from another .rb file

Probably more like this:

module Decisioning
module Decision
class OfferProxy

def self.my_method
"some value"
end

end
end
end

class TestFile

include Decisioning::Decision

def test
puts OfferProxy.my_method
end

end

TestFile.new.test

Or...

module Decisioning
module Decision
class OfferProxy

def my_method
"some value"
end

end
end
end

class TestFile

include Decisioning::Decision

def test
offer_proxy = OfferProxy.new
puts offer_proxy.my_method
end

end

TestFile.new.test

Including a Ruby class from a separate file

Modules serve a dual purpose as a holder for functions and as a namespace. Keeping classes in modules is perfectly acceptable. To put a class in a separate file, just define the class as usual and then in the file where you wish to use the class, simply put require 'name_of_file_with_class' at the top. For instance, if I defined class Foo in foo.rb, in bar.rb I would have the line require 'foo'.

If you are using Rails, this include often happens automagically

Edit: clarification of file layout

#file: foo.rb
class Foo
def initialize
puts "foo"
end
end

...

#file: bar.rb
require 'foo'

Foo.new

If you are in Rails, put these classes in lib/ and use the naming convention for the files of lowercase underscored version of the class name, e.g. Foo -> foo.rb, FooBar -> foo_bar.rb, etc.

As of ruby version 1.9 you can use require_relative, to require files relatively to the file you are editing.

Loading module into User Model in Rails

You seem to have missunderstood what what modules and classes do in Ruby. In Ruby a module is simply an object that wraps a set of methods and constants.

A module can extend other modules, classes and objects and can be included in classes thus implementing multiple inheritance. Modules in Ruby fill the role that traits, namespaces and singletons do in other languages.

Classes are actually modules (Module is part of the ancestors chain of Class) with the key difference that you can make instances of a class and that class can inherit from a single other class and cannot extend other objects or be included.

The code example here actually doesn't make sense. If you want to declare a method that will be available to classes that include a module you want to declare it in the module itself:

module MyModule
def some_method
# do something
end
end

When you then call User#another_method it will look in the ancestors chain of the User class until it finds the method which is defined in MyModule.

module MyModule
class MyClass
def some_method
# do something
end
end
end

Will actually definte the class MyClass with an instance method that is only available to instances of MyClass. The only thing that the module does here is change the module nesting so that the class is defined in MyModule instead of the global namespace.

How do I import ruby classes into the main file?

In order to include classes, modules, etc into other files you have to use require_relative or require (require_relative is more Rubyish.) For example this module:

module Format

def green(input)
puts"\e[32m#{input}[0m\e"
end
end

Now I have this file:

require_relative "format" #<= require the file

include Format #<= include the module

def example
green("this will be green") #<= call the formatting
end

The same concept goes for classes:

class Example

attr_accessor :input

def initialize(input)
@input = input
end

def prompt
print "#{@input}: "
gets.chomp
end
end

example = Example.new(ARGV[0])

And now I have the main file:

require_relative "class_example"

example.prompt

In order to call any class, or module from another file, you have to require it.

I hope this helps, and answers your question.

How to reference a method in another Ruby code file?

If you are using Ruby 1.9 or later, this is the simplest way to do it:

require_relative 'somelogic'

If you want your code to work in 1.9 and older versions of Ruby, you should do this instead:

require File.join File.dirname(__FILE__), 'somelogic'

Whichever line you choose, you should put it at the top of your ruby file. Then any classes, modules, or global variables defined in somelogic.rb will be available to your program.

What is the proper way to add a method to a built-in class in ruby?

tenebrousedge there was probably hinting at refinements.

Or, rather, not patching String at all. More often than not, monkeypatching creates more problems than it solves. What if String already knew alpha? and it did something different?

For example, future versions of ruby might add String#alpha? that will handle unicode properly

'新幹線'.alpha? # => true

and your code, as it is, would overwrite this built-in functionality with an inferior version. Now your app is breaking in all kinds of places, because stdlib/rails assumes the new behaviour. Chaos!

This is to say: avoid monkeypatching whenever possible. And when you can't avoid, use refinements.

Accessing a variable declared in another rb file

The best way to export data from one file and make use of it in another is either a class or a module.

An example is:

# price.rb
module InstancePrices
PRICES = {
'us-east-1' => {'t1.micro' => 0.02, ... },
...
}
end

In another file you can require this. Using load is incorrect.

require 'price'

InstancePrices::PRICES['us-east-1']

You can even shorten this by using include:

require 'price'

include InstancePrices
PRICES['us-east-1']

What you've done is a bit difficult to use, though. A proper object-oriented design would encapsulate this data within some kind of class and then provide an interface to that. Exposing your data directly is counter to those principles.

For instance, you'd want a method InstancePrices.price_for('t1.micro', 'us-east-1') that would return the proper pricing. By separating the internal structure used to store the data from the interface you avoid creating huge dependencies within your application.

Calling another ruby file that is not a gem

In 99% of all cases when a computer tells you that it couldn't find a thing, it is because the thing isn't there. So, the first thing you need to check is whether there actually is a file named TestClass.rb somewhere on your filesystem.

In 99% of the rest of the cases, the computer is looking in the wrong place. (Well, actually, the computer is usually looking in the right place, but the thing it is looking for is in the wrong place). require loads a file from the $LOAD_PATH, so you have to make sure that the directory that the file TestClass.rb is in actually is on the $LOAD_PATH.

Alternatively, if you do not want to require a file from the $LOAD_PATH but rather relative to the position of the file that is doing the requireing, then you need to use require_relative.

Note, however, that your code won't work anyway, since say_hello is in instance method of instances of the TestClass class, but you are calling it on the main object, which is an instance of Object, not TestClass.

Note also that standard naming conventions of Ruby files are snake_case, in particular, the snake_case version of the primary class/module of the file. So, in your case, the file should be named test_class.rb. Also, require and require_relative figure out the correct file extension for themselves, so you should leave off the .rb. And thirdly, standard Ruby coding style is two spaces for indentation, not four.

None of these will lead to your code not working, of course, since it is purely stylistic, but it may lead to people being unwilling to answer your questions, since it shows that you don't respect their community enough to learn even the most basic rules.



Related Topics



Leave a reply



Submit