In Ruby on Rails we can state a helper method in controllers e.g.
# app/controllers/my_controller.rb
class MyController < ApplicationController
helper_method :helper_method_name
...
private
def helper_method_name
...
end
end
and in helpers e.g.
# app/helpers/my_helper.rb
class MyHelper
def helper_method_name
...
end
end
What's the difference (in relation to access, usage, etc.)?
The method helper_method is to explicitly share some methods defined in the controller to make them available for the view.
This is used for any method that you need to access from both controllers and helpers/views (standard helper methods are not available in controllers).
As ray said. You only want to use the helper_method when you really need to use it in both the controllers and helpers/views.
Generally, you want to use controller concerns and the helpers(views) for the respective methods as that's the convention.
The callback is like below.
class User
include UserSettable
before_action :set_user
def show
[Something with #user]
end
end
class Group
include UserSettable
before_action :set_user
...
end
And the set_user is like below. And this method is defined in the controller concern.
module UserSettable
extend ActiveSupport::Concern
def set_user
#user = User.find(params[:id])
end
end
I have three questions.
How do I pass params to callback method?
Can the instance variable defined in concern be used in controller?
Does this implementation deviate from the usual usage of rails?
How do I pass params to callback method?
params of request will automatically be available to action. You don't need to pass it explicitly. Your code snippet is perfect use case of how it should be used.
Can the instance variable defined in concern be used in controller?
You mean controller's concern. I think the instance variable defined there should be available. Can you give an example of what you are trying to achieve?
Does this implementation deviate from the usual usage of rails?
No
I need to create a controller instance from another controller for using its methods. When I creating
c = SomeController.new
c.some_method
some_method use params[], and then I have an error NoMethodError: undefined method 'parameters' for nil:NilClass.
How can I pass params to the controller?
The thing you are trying to do it not recommended any framework. You probable have some code that you wanted in multiple controllers. To achieve your desired behavior, extract the common code to library can call that in any controller you want.
You don't instantiate controllers in Rails - its done by the router when it matches a request to a route.
Its just not done because it violates the way MVC in Rails works - one request = one controller. You also need to pass the entire env hash from rack into the controller for it even work properly.
But really - don't. There are much better ways.
If you need to share a method between controllers there are better ways such as using inheritance:
class ApplicationController
def some_method
end
end
class FooController < ApplicationController
end
class BarController < ApplicationController
end
Or mixins:
# app/controllers/concerns/foo.rb
module Foo
def some_method
end
end
class BarController < ApplicationController
include Foo
end
class BazController < ApplicationController
include Foo
end
If you instead need to move a request from one controller action to another you should be redirecting the user.
I created a helper method for some simple calculation. This helper method will just return an integer. I need the helper in both controllers and views.
Unfortunately, it work well in views but not in controllers. I get the undefined local variable or method error. How can I fix it?
Thanks all
In order to use same methods in both controller and views Add you method in application_controller.rb and make it helper methods.
For example
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
#protect_from_forgery # See ActionController::RequestForgeryProtection for details
helper_method :current_user
def current_user
session[:user]
end
end
Now you can use method current_user in both controllers & views
I use a following solution. Because I think helper's methods shoud be stored in an appropriate helper module.
module TestHelper
def my_helper_method
#something
end
end
class SomeController < ApplicationController
def index
template.my_helper_method
end
end
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