I would like to know what is the right way to use a class with namespace in rails 6.
I have the follow, but it isn't working and I'm receiving the error:
"Uninitialized constant ProductsController::Operations Did you mean? ProductsController::Options"
#app/operations/create.rb
module Operations
class Create
def self.foo
...
end
end
end
#app/controllers/products_controller.rb
class ProductsController < ApplicationController
def create
Operations::Create.foo
end
end
Can you help me please?
Your module should be inside of any folder. For example app/services/operations/create.rb (any name will work) with the same content you have:
module Operations
class Create
def self.foo
...
end
end
end
and call it Operations::Create.foo.
Also make sure you restart spring with spring stop.
Related
my jsonwebtokenauthentication.rb is in (app/lib.jsonwebtokenauthentication.rb):
class JsonWebTokenAuthentication
def some_method
#logic of the method
end
end
I am trying to access the above JsonWebTokenAuthentication method's in my registrations_controller.rb(app/controllers/api/v1/registrations_controller.rb)
class Api::V1::RegistrationsController < Api::V1::BaseController
def create
auth_token = JsonWebTokenAuthentication.some_method({user_id: user.id})
end
end
end
How can we use the class method specified inside lib folder in rails project.
Firstly if you want to use the RoR framework you are supposed to name your files using the Ruby Style guide. Also JsonWebTokenAuthentication looks more like a module, not a class for me, could you please clarify why you choose the class here?
I would suggest adding the some_method to the ApplicationController instead. Another option is to add a json_web_token_authentication.rb to the app/services/ but using the same namespace as the controller.
I'm relatively new to Rails and am working on creating a simple user authentication system to get to grips with how Rails works.
I'm currently at the point where I'd like to create some methods that I can use in my controllers like so:
is_logged? # => true
and
current_user_id # => 6
These would be used to interact with sessions, mainly so I'm not repeating myself in the controller.
Where would I define these functions and how would I include them in a controller?
Thanks a lot in advance for any help.
Method 1
You can define these method in helper files, inside app/helpers/my_module.rb. You can create a module there, put all the methods inside of it, and then include the modules in your control to use these method.
module MyMoule
def is_logged?
...
end
end
Then in you class include the module
class MyClassController < ApplicationController
include MyModule
def my_method
#Use it like this
logged_in = MyModule.is_logged?
end
end
Method 2
If you using session related stuff you can always put them inside application_controller.rb. And since all your controller will inherit ApplicationController the methods will be available to you.
class ApplicationController < ActionController::Base
def is_logged?
...
end
end
In your other controller you can use them directly.
class MyClassController < ApplicationController
def my_method
logged_in = is_logged?
end
end
I have a controller: "/app/controllers/analyst/test_orders_controller.rb".
In this file I have:
class Analyst::TestOrdersController < ApplicationController
def new
#order = Order.new
end
end
But I have an error:
uninitialized constant Analyst::TestOrdersController::Order
But I don't want to use Analyst::TestOrdersController::Order.new, I just want to use Order.new. It is strange. What is the problem?
Use ::Order.new
The interpreter is looking for the definition of Order under the Analyst module namespace, this happens because the application models are loaded lazily so the file models/order.rb has not been read yet. Adding the general namespace tells it search for the definition in the Rails paths.
The way to confirm this is to add some random function call in the Order model body and see that it's not executed unless you call ::Order explicitly.
try:
module Analyst
class TestOrdersController < ApplicationController
def new
#order = Order.new
end
end
end
I think it has to do with module nesting:
https://cirw.in/blog/constant-lookup
I want to add a filter to the ApplicationController but I want to do it within my gem.
What I want to avoid is the following:
class ApplicationController < ActionController::Base
include MyGem
end
I do not want that. I don't want to have to include my module in the source code.
I am having issues though.
Here is the relevant code:
lib/correlation_id/controller_extension
module CorrelationId
module ControllerExtension
def self.included(klass)
klass.class_eval do
after_filter :pass_correlation_id
end
end
def pass_correlation_id
correlation_id = request.headers['Correlation-ID'] || SecureRandom.uuid
headers['Correlation-ID'] = correlation_id
end
end
end
ApplicationController.send :include, CorrelationId::ControllerExtension
lib/correlation_id.rb
require 'correlation_id/controller_extension'
module CorrelationId
end
Now, when I'm in the test/dummy directory, which is a test rails app for my gem, I try to boot up the server using rails s and I get the following error:
/correlation_id/lib/correlation_id/controller_extension.rb:17:in `<top (required)>': uninitialized constant ApplicationController (NameError)
I'm clearly having problems with referencing ApplicationController to monkey-patch it.
How would I manage this? I want my gem to be self-contained.
The following code works. What I did was prematurely create ApplicationController with the appropriate inheritance. Note, many people use the rails-api gem, so I factored in them to ensure the fact that it would work.
Also, note: You must inherit from a class because otherwise ApplicationController will be a usual class that doesn't understand what after_filter is.
module CorrelationId
module ControllerExtension
def self.included(klass)
klass.class_eval do
after_filter :pass_correlation_id
end
end
def pass_correlation_id
correlation_id = request.headers['Correlation-ID'] || SecureRandom.uuid
headers['Correlation-ID'] = correlation_id
end
def self.base_controller_inheritance
if Gem::Specification.find_all_by_name('rails-api').any?
ActionController::API
else
ActionController::Base
end
end
end
end
class ApplicationController < CorrelationId::ControllerExtension.base_controller_inheritance
include CorrelationId::ControllerExtension
end
I imagine there might be a better way to check if they are using ActionController::API and if so, please do share, but as of now, this seems like the most solid way to do it.
I have a controller having more than 1000 lines of code.
Right not I am doing Code review for this controller.
I arrange my methods according to the module.
Now I realise that my controller is not easy to maintain and so I want to something like following
class UsersController < ApplicationController
#Code to require files here
#before filter code will goes here
#############Here i want to call that partial like things. following is just pseudo #########
history module
account module
calendar module
shipment module
payment module
####################################################################
end #end of class
this help me so much to maintained the code as when i change history module i am sure that my account module is unchanged.I know CVS but i prefer 50 copies of each module instead 200 copies of my users_controller.rb itself.
P.S. :- I would like Affirmative answer.please don't answer like, you should use different controller for different module.....bla...bla...bla... as it's not possible for me to do so.
EDIT:- My Versions Are
rails -v
Rails 2.3.4
ruby -v
ruby 1.8.6 (2008-08-11 patchlevel 287) [i386-linux]
This should work for you:
app/controllers/some_controller.rb
class SomeController < ApplicationController
include MyCustomMethods
end
lib/my_custom_methods.rb
module MyCustomMethods
def custom
render :text => "Rendered from a method included from a module!"
end
end
config/routes.rb
# For rails 3:
match '/cool' => "some#custom"
# For rails 2:
map.cool 'cool', :controller => "some", :action => "custom"
Fire up your app and hit http://localhost:3000/cool, and you'll get your custom method included from a module.
Assuming from you pseudocode that you are referring to Ruby modules, and not something else, just put all your requires/modules in a separate module and include that or have your UsersController inherit from a base class if you are reusing those files. In the first case you can think of a module as a mix-in and it is designed for exactly the modularity you want.
module AllMyStuff
include History
include Account
...
end
class UsersController < ApplicationController
include AllMyStuff
def new
end
...
end
or you can inherit from a base controller,in this case its probably a reasonable solution.
def BaseController < ActionController
include history
include account
end
def UsersController < BaseController
# modules available to this controller by inheritance
def new
end
...
end
I tried the following method and I have it running, maybe it suits for you:
app/user_controller.rb
require 'index.rb'
class UsersController < ApplicationController
# some other code
end
app/index.rb
class UsersController < ApplicationController
def index
#users = User.all
end
end
MY ENV: rails 3 beta4