Using helper in controller in Rails 4.2.4 - ruby-on-rails

I'm confused by the rails documentation that I'm reading here. In particular, this sentence:
By default, each controller will include all helpers. These helpers
are only accessible on the controller through .helpers
What is this .helpers that it is referring to? I have a helper defined in app/helpers/areas_helper.rb:
module AreasHelper
def my_helper
puts "Test from helper"
end
end
I would like to use this helper in app/controllers/locations_controller.rb:
class LocationsController < ApplicationController
def show
helpers.my_helper
end
end
However, I get a method undefined error. How is this .helpers supposed to be used?
I know there are other ways to get access to helpers in controllers, but I'm specifically asking about this piece of documentation and what it's trying to say.

You're meant to include the helper class in the controller:
#app/controllers/locations_controller.rb
class LocationsController < ApplicationController
include AreasHelper
def show
my_helper
end
end

This feature was introduced in Rails 5 with following PR
https://github.com/rails/rails/pull/24866
So, we can use this feature from Rails 5 and onwards and not in Rails 4.x.

Related

NameError (uninitialized constant Api::V1::RegistrationsController::JsonWebTokenAuthentication):

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.

Ruby On Rails - Using concerns in controllers

Possible Noob Warning: New to RoR
I am trying to use concerns in RoR. Right now I just have a very simple concern writen
#./app/controllers/concerns/foo.rb
module Foo
extend ActiveSupport::Concern
def somethingfoo
puts "Ayyyy! Foo"
end
end
When I try and use this concern in my controller I get a undefined method error
#./app/controllers/foo_controller.rb
class FooController < ApplicationController
include Foo
def show
Foo.somethingfoo # undefined method 'somethingfoo' for Foo:Module
render plain: "Ohh no, It doesnt even show me because of the error above me"
end
end
To my knowledge somethingfoo should be called but it is not. I have also tried defining somethingfoo in a included do ... end block in the concern but this does not work either.
Is there something I am missing? Can concerns not be used like this with controllers?
If you include modules (extended by ActiveSupport::Concern or not), the methods of that module become instance methods of the including class/module.
Your Controller method should hence read
def show
somethingfoo
render plain: "Yeah, I'm shown!"
end

Where to put Ruby helper methods for Rails controllers?

I have some Ruby methods certain (or all) controllers need. I tried putting them in /app/helpers/application_helper.rb. I've used that for methods to be used in views. But controllers don't see those methods. Is there another place I should put them or do I need to access those helper methods differently?
Using latest stable Rails.
You should define the method inside ApplicationController.
For Rails 4 onwards, concerns are the way to go. There was a decent article which can still be viewed via the Wayback Machine.
In essence, if you look in your controllers folder you should see a concerns sub-folder. Create a module in there along these lines
module EventsHelper
def do_something
end
end
Then, in the controller just include it
class BadgeController < ApplicationController
include EventsHelper
...
end
you should define methods inside application controller, if you have few methods then you can do as follow
class ApplicationController < ActionController::Base
helper_method :first_method
helper_method :second_method
def first_method
... #your code
end
def second_method
... #your code
end
end
You can also include helper files as follow
class YourController < ApplicationController
include OneHelper
include TwoHelper
end
You can call any helper methods from a controller using the view_context, e.g.
view_context.my_helper_method
Ryan Bigg response is good.
Other possible solution is add helpers to your controller:
class YourController < ApplicationController
include OneHelper
include TwoHelper
end
Best Regards!
Including helpers in controller will end-up exposing helper methods as actions!
# With new rails (>= 5)
helpers.my_helper_method
# For console
helper.my_helper_method

Is there any partial kind of thing for controllers in Ruby on Rails

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

"undefined method" when calling helper method from controller in Rails

Does anyone know why I get
undefined method `my_method' for #<MyController:0x1043a7410>
when I call my_method("string") from within my ApplicationController subclass? My controller looks like
class MyController < ApplicationController
def show
#value = my_method(params[:string])
end
end
and my helper
module ApplicationHelper
def my_method(string)
return string
end
end
and finally, ApplicationController
class ApplicationController < ActionController::Base
after_filter :set_content_type
helper :all
helper_method :current_user_session, :current_user
filter_parameter_logging :password
protect_from_forgery # See ActionController::RequestForgeryProtection for details
You cannot call helpers from controllers. Your best bet is to create the method in ApplicationController if it needs to be used in multiple controllers.
EDIT: to be clear, I think a lot of the confusion (correct me if I'm wrong) stems from the helper :all call. helper :all really just includes all of your helpers for use under any controller on the view side. In much earlier versions of Rails, the namespacing of the helpers determined which controllers' views could use the helpers.
I hope this helps.
view_context is your friend, http://apidock.com/rails/AbstractController/Rendering/view_context
if you wanna share methods between controller and view you have further options:
use view_context
define it in the controller and make available in view by the helper_method class method http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method
define it in a shared module and include/extend
Include ApplicationHelper in application_controller.rb file like this:
class ApplicationController < ActionController::Base
protect_from_forgery
include ApplicationHelper
end
This way all the methods defined in application_helper.rb file will be available in the controller.
You can also include individual helpers in individual controllers.
Maybe I'm wrong, but aren't the helpers just for views? Usually if you need a function in a controller, you put it into ApplicationController as every function there is available in its childclasses.
As said by gamecreature in this post:
In Rails 2 use the #template variable.
In Rails 3 use the controller method view_context
helpers are for views, but adding a line of code to include that helper file in ApplicationController.rb can take care of your problem. in your case, insert the following line in ApplicationController.rb:
include ApplicationHelper
As far as i know, helper :all makes the helpers available in the views...
Try appending module_function(*instance_methods) in your helper modules, after which you could directly call those methods on the module itself.
though its not a good practice to call helpers in controller since helpers are meant to be used at views
the best way to use the helpers in controller is to make a helper method in application_controller and call them to the controller,
but even if it is required to call the helper in a controller
then Just include the helper in the controller
class ControllerName < ApplicationController
include HelperName
...callback statements..
and call the helper methods directly to the controller
module OffersHelper
def generate_qr_code(text)
require 'barby'
require 'barby/barcode'
require 'barby/barcode/qr_code'
require 'barby/outputter/png_outputter'
barcode = Barby::QrCode.new(text, level: :q, size: 5)
base64_output = Base64.encode64(barcode.to_png({ xdim: 5 }))
"data:image/png;base64,#{base64_output}"
end
Controller
class ControllerName < ApplicationController
include OffersHelper
def new
generate_qr_code('Example Text')
end
end
hope this helps !
I had the same problem...
you can hack/bodge around it, put that logic into a model, or make a class specially for it. Models are accessible to controllers, unlike those pesky helper methods.
Here is my "rag.rb" model
class Rag < ActiveRecord::Base
belongs_to :report
def miaow()
cat = "catattack"
end
end
Here is part of my "rags_controller.rb" controller
def update
#rag = Rag.find(params[:id])
puts #rag.miaow()
...
This gave a catattack on the terminal, after I clicked "update".
Given an instantiation, methods in the model can be called. Replace catattack with some codes. (This is the best I have so far)
:helper all only opens helpers up to views.
This shows how to make a class and call it.
http://railscasts.com/episodes/101-refactoring-out-helper-object?autoplay=true
Try this to access helper function directly from your controllers view_context.helper_name
You can include your helper methods into a controller with a helper keyword syntax
class MyController < ApplicationController
helper ApplicationHelper
end

Resources