How to use modules in Rails application - ruby-on-rails

I just created a module location.rb inside /lib folder with following contents:
module Location
def self.my_zipcode()
zip_code = "11215"
end
end
And now in my controller i am trying to call "my_zipcode" method:
class DirectoryController < ApplicationController
def search
require 'location'
zip_code = Location.my_zipcode()
end
end
But it throws an error:
undefined method `my_zipcode' for Location:Module

You can also add the following to your config/application.rb
config.autoload_paths += %W(#{config.root}/lib)
And it should autoload your module without having to restart rails.

You might have to restart the rails server for it to recognize stuff in the lib directory.

Related

Rails: controller cannot recognize class from module/namespace - uninitialized constant

I've created directory for API logic: app/api/EtherumAPI/V1 and put there following code:
module EtherumAPI
module V1
class Request
class << self
def trancation
end
end
end
end
end
Registered in my application.rb:
config.autoload_paths << "#{Rails.root}/app/api"
config.eager_load_paths << "#{Rails.root}/app/api"
And try to call it inside my controller:
def index
#test = EtherumAPI::V1::Request
#test.trancation
end
But I got this error:
uninitialized constant HomeController::EtherumAPI
I tried also something like "include EtherumAPI::V1" but it didn't succeed as well. How can I fix it and be able to call methods from Request class?
First off you can get rid of:
config.autoload_paths << "#{Rails.root}/app/api"
config.eager_load_paths << "#{Rails.root}/app/api"
All the subdirectories of app are by default auto-load paths. Occasionally the auto-loader gets "stuck" and will not pick up newly added directories. You can usually fix that by restarting the rails server and spring ($ spring stop).
There are two issues at play here. The first is inflection. Rails inflects file names from classes by camelizing the class name. Unfortunately this does not work automatically for acronyms as ABC -> a_b_c.rb.
So for the autoloader to look for EtherumAPI in etherum_api.rb you need to add an inflection:
# config/initializers/inflections.rb
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'EtherumAPI'
end
The second issue is that the module names must match the actual path to the file.
# app/api/etherum_api/v1/request.rb
module EtherumAPI
module V1
class Request
class << self
def trancation
end
end
end
end
end

Name error uninitialized constant module rails

I have a rails application in that I have modules inside /app/adapters/UDB/ folder. The module is not loading. I have added the following in application.rb
config.autoload_paths += Dir["#{config.root}/app/adapters/**/*"]
I am calling module from model file /models/userinvite.rb
def update_cassandra
ypusers = UDB::YpRewards.new.ypusers
ypusers.execute("UPDATE invitation_backlog SET invitation_code = '#{invitation_code}', invitation_sent_date = #{invitation_sent_date.to_i * 1000}, invited_by = '#{invited_by}' WHERE email_address = '#{email}'")
end
/app/adapters/UDB/yp_rewards.rb
module UDB
class YpRewards
def initialize
end
def ypusers
#ypusers ||= UDB::Connection.new.connection.connect('ypusers')
end
...
Please help me solving it.
I think the issue is with module name.
Your module name is UDB, then you can load this module by specifying its name in smallcase letters as per rails naming convention (camelcasing)
config.autoload_paths += %W( #{config.root}/app/adapters/u_d_b)
Try including the module in your UserInvite model,
include UDB
This is a good site to know more about the placement and usage of modules.

Using Libraries in Rails (4.1.x) Engines?

So the core issue at heart here is the following message:
`<class:ApplicationController>': uninitialized constant Xaaron::Core (NameError)
So I think some of the steps I have done will be redundant, but I am new to trying to add code to my library folder in a rails engine, in rails its rather easy. But here its not so much.
So here is what I have done:
in:
xaaron/
lib/
xaaron/
I have a directory called core/ with a file called loder.rb.
Inside of core is a directory called controllers and in side there is a file called user_controller which looks like:
module Xaaron
module Core
module UserController
def assign_to_member_group(user)
memeber = Xaron::Group.find('member')
user.add_group = memeber.group_name
end
end
end
end
To load this I have a loader file:
module Xaaron
module Core
module Loader
include Xaaron::Core::Controllers::UserController
end
end
end
Which I do not think is needed because in the engine.rb file I do: config.autoload_paths << File.expand_path("../xaaron/core/**", __FILE__) which just goes up one directory to the lib/ directory and loads xaaron/core/ and everything in it (or so I thought).
This loader.rb file is included in the ApplicationController
module Xaaron
class ApplicationController < ActionController::Base
...
include Xaaron::Core::Loader
...
end
end
So:
Whats the proper way to load my "core" library
Why am I getting the error above?
I guess your problem is with config.autoload_paths << File.expand_path("../xaaron/core/**", __FILE__). It expands into smth like Rails.root/lib/engine_name/xaaron/core/** and your lib path should be Rails.root/lib/xaaron/core. So, in your case, lib path should be config.autoload_paths << File.expand_path("../../xaaron/core", __FILE__)
Moreover, beeing within your ApplicationController, it is enough to include include Core::Loader, because you're already within Xaaron namespace.
Before you'll start working with controllers, try just call your module Xaaron::Core::Loader within rails console.

Learning About the lib Directory in Rails

I am very new to Rails, and am trying to learn how the /lib/ directory in Rails works - and how to reference variables defined in the /lib/ directory for use in a view.
I have a file called helloworld.rb and it's saved in the /lib/ directory in Rails.
The helloworld.rb file has the following code:
module HelloWorld
def hello
#howdy = "Hello World!"
end
end
I want to be able to display the results of this method on a view called index.html.erb, so I include the following code in the index_helper.rb file:
module IndexHelper
require 'helloworld'
end
Also, I include the following code on the view index.html.erb:
<%= #howdy %>
What am I missing?
You need to call Helloworld::hello in order for it to create your instance variable.
maybe you could put it in a before_filter in your controller
require 'helloworld'
class FooController < Application::Controller
before_filter :setup_hello , [:only=>:create, :edit ]
def create
# whatever
end
def edit
#whatever
end
def setup_hello
HelloWorld::hello
end
end
So now, every time you either your edit or create action, 'setup_hello' is executed, which calls the hello method in your module, and sets the #hello instance variable.
You should any of these lines to config/application.rb file.
module [App name]
class Application < Rails::Application
# Dir.glob("./lib/*.rb").each { |file| require file }
# config.autoload_paths += %W(#{Rails.root}/lib)
end
end
Uncomment any of commented lines. Both of them do same work.
Dir.glob finds all .rb files in app and require each file in rails app.
Also config.autoload_paths also load all files in lib folder.
You have to add the lib folder to the auto-load path in config/application.rb
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/lib)

Where to put custom classes to make them globally available to Rails app?

I have a class that I'm trying to use in my controller in the index action.
To simplify it, it looks like this
class PagesController < ApplicationController
def index
#front_page = FrontPage.new
end
end
FrontPage is a class that I have defined. To include it, I have placed it in the /lib/ folder. I've attempted to require 'FrontPage', require 'FrontPage.rb', require 'front_page', and each of those with the path prepended, eg require_relative '../../lib/FrontPage.rb'
I keep getting one of the following messages: cannot load such file -- /Users/josh/src/ruby/rails/HNReader/lib/front_page or
uninitialized constant PagesController::FrontPage
Where do I put this file/how do I include it into a controller so that I can instantiate an object?
This is Rails 3.1.3, Ruby 1.9.2, OS X Lion
You should be able to use require 'front_page' if you are placing front_page.rb somewhere in your load path. I.e.: this should work:
require 'front_page'
class PagesController < ApplicationController
def index
#front_page = FrontPage.new
end
end
To check your load path, try this:
$ rails console
ree-1.8.7-2011.03 :001 > puts $:
/Users/scottwb/src/my_app/lib
/Users/scottwb/src/my_app/vendor
/Users/scottwb/src/my_app/app/controllers
/Users/scottwb/src/my_app/app/helpers
/Users/scottwb/src/my_app/app/mailers
/Users/scottwb/src/my_app/app/models
/Users/scottwb/src/my_app/app/stylesheets
# ...truncated...
You can see in this example, the first line is the project's lib directory, which is where you said your front_page.rb lives.
Another thing you can do is add this in your config/application.rb:
config.autoload_paths += %W(#{config.root}/lib)
That should make it so you don't even need the require; instead Rails will autoload it then (and everything else in your lib dir, so be careful).
The file was named FrontPage.rb. Changing the name to 'front_page.rb', but leaving the class name as 'FrontPage' resolved the issue.
We just need to load the file,
class PagesController < ApplicationController
require 'front_page.rb'
def index
#front_page = FrontPage.new
end
end
lib/front_page.rb
class FrontPage
end
We can also set the application.rb to autoload these files
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
Second option would be a preferable solution.

Resources