I tried TO Google Can I redirect_to in rails modules but couldn't come up with anything. Basically, I have a method that I am going to use across a couple of Controllers.
lib/route_module.rb
module RouteModule
def self.user_has_active_chocolate(c_id, u_id)
chocolate_id = c_id
user_id = u_id
unless UserChocolate.where(id: chocolate_id).empty?
if UserChocolate.where(id: chocolate_id).last.active?
true
else
false
# BREAKS OVER HERE...
redirect_to "/user/new-chocolate/#{user_id}"
end
else
false
redirect_to "/admin"
end
end
end
app/controllers/user_controllers.rb
include RouteModule
before_filter :thingz, only: [:display_user_chocolate]
# private
def thingz
RouteModule.user_has_active_chocolate(params["chocolate_id"], params["user_id"])
end
But... whenever I run this... It will break as soon as it hit's redirect_to.
undefined method `redirect_to' for RouteModule:Module
My other option is use ActiveSupport::Concerns but I just trouble converting this Module into a Concern.
When you include a module, it acts as a mixin. That said, you include and get all the methods of the module in the context of your class. The proper way would be:
module RouteModule
def user_has_active_chocolate(c_id, u_id) # NO self
...
end
end
And in the class:
include RouteModule
def thingz
# NO module method call (NO RouteModule)
user_has_active_chocolate(params["chocolate_id"], params["user_id"])
end
Related
How do I access things outside of a class method in rails? I get an error like undefined method do_something_else
module Thing
def self.do_something
do_something_else
end
def do_something_else
end
end
Here's a good reference that shows the difference between class_methods/singleton_methods and instance_methods.
In your case, you cannot access the instance method(do_something_else) without an instance.
To solve this, you have to include the module in a class and use an instance of that class.
module Thing
def self.do_something
Logic.new.do_something_else
end
def do_something_else
#perform the logic and actions here
end
end
class Logic
include Thing
end
If you would like to think of it differently though, here's what I'd propose:
module Thing
def self.do_something_else
# perform your logic and actions here
end
def do_something
# this is possible because do_something_else is defined on the module Thing
Thing.do_something_else
end
end
Try this
def self.do_something
Thing.new.do_something_else
end
I need more fine grain control on the order of callbacks in my controllers. Currently Rails only let you use append|prepend_before|after_action, but this is just extremely bad if you want to add a module with its dedicated callbacks.
I am trying to understand how AbstractController::Callbacks work, and I'm trying to register a new type of callback, that would be executed at a specific moment, taking advantage of Rail's controllers syntax for adding a callback (only/except + list of actions, etc.).
You can think of it as a custom Access Control feature, but this question isn't about access control, please refrain answerbombing with gems like Cancan.
class ApplicationController
include xxx
include MyModuleWithCallbacks
include yyy
...
end
class MyController < ApplicationController
prepend_before_action :something_before_my_callbacks
my_callback_list :custom_callback, only: [:index, :show]
before_action :something_after_my_callbacks
# Goal : the order of above callbacks should NOT matter, my_callback does not depend on ActionController process_action callback list
end
module MyModuleWithCallbacks
extend ActiveSupport::Concern
extend AbstractController::Callbacks
included do
around_action :perform_if_condition
def perform_if_condition
run_callbacks :my_callback_list do
if my_callbacks_went_good?
yield # And run the controller's before_callbacks
else
# log, render error page, etc.
end
end
end
# This is the hard part register the callback, I tried
class_methods do
define_method :my_callback_list do |*names, &blk|
_insert_callbacks(names, blk) do |name, options|
set_callback(:my_callback_list, :before, name, options)
end
end
end
The current error is
undefined method `_my_callbacks_list_callbacks' for PublicController:Class
I am taking my inspiration from the source code of AbstractController::Callbacks but I'm not sure I understand what's going on there ^^"
I saw some upvotes so here is my current solution :
With the example of a very lightweight Access control method, the original name of my_callback was access_control
# controllers/concerns/access_control.rb
module AccessControl
extend ActiveSupport::Concern
class_methods do
define_method :my_callback do |*names, &blk|
_insert_callbacks(names, blk) do |name, options|
set_callback(:my_callback, :before, name, options)
end
end
end
included do
define_callbacks :my_callback
def perform_if_access_granted
run_callbacks :my_callback do
if #access_denied and not #access_authorized and not god_mode?
#request_authentication = true unless user_signed_in?
render(
file: File.join(Rails.root, 'app/views/errors/403.html'),
status: 403,
layout: 'error')
else
yield
end
end
end
Then in your other controllers that include the module (again with Access control example)
# controllers/your_controller.rb
class YourController < SeekerController
your_callback do
set_entity
allow_access_to_entity(#entity)
end
I have two Helpers, ExamsHelper and ResultsHelper
exams_helper.rb
module ExamsHelper
def get_data
...
end
end
results_helper.rb
module ResultsHelper
def find_result
...
end
end
Is it possible to access the get_data method in ResultsHelper.
I know that if I am declaring it on the ApplicationHelper, I can access it. Is there any other solution for it?
You can always use include:
module ResultsHelper
include ExamsHelper
def find_result
get_data # works
end
end
In my rails projects, I often use this sort of behavior in my classes and models:
class Whatever
class WhateverError < StandardError; end
def initialize(params={})
raise WhateverError.new("Bad params: #{params}") if condition
# actual class code to follow
end
end
The trouble is, this is both hugely repetitive and fairly verbose. I'd love it if I could just do this whenever I need to raise a class-specific error:
class ErrorRaiser
include ClassErrors
def initialize(params={})
error("Bad params: #{params}") if condition
error if other_condition # has default message
# actual class code to follow
end
def self.class_method
error if third_condition # class method, behaves identically
end
end
I'm having major trouble creating such a module. My sad early attempts have tended to look something like the below, but I'm pretty confused about what's available within the scope of the module, how to dynamically create classes (within methods?) or whether I have straightforward access to the "calling" class at all.
My basic requirements are that error be both a class method and an instance method, that it be "namespaced" to the class calling it, and that it have a default message. Any thoughts/help? Is this even possible?
module ClassErrorable
# This and the "extend" bit (theoretically) allow error to be a class method as well
module ClassMethods
def self.error(string=nil)
ClassErrorable.new(string).error
end
end
def self.included(base)
set_error_class(base)
base.extend ClassMethods
end
def self.set_error_class(base)
# I'm shaky on the scoping. Do I refer to this with # in a class method
# but ## in an instance method? Should I define it here with # then?
##error_class = "##{base.class}Error".constantize
end
def self.actual_error
# This obviously doesn't work, and in fact,
# it raises a syntax error. How can I make my
# constant a class inheriting from StandardError?
##actual_error = ##error_class < StandardError; end
end
def initialize(string)
#string = string || "There's been an error!"
end
def error(string=nil)
raise ##actual_error.new(string)
end
end
How about something like this (written in pure Ruby; it could be refactored to use some Rails-specific features like .constantize):
module ClassErrorable
module ClassMethods
def error(message = nil)
klass = Object::const_get(exception_class_name)
raise klass.new(message || "There's been an error!")
end
def exception_class_name
name + 'Error'
end
end
def self.included(base)
base.extend ClassMethods
Object::const_set(base.exception_class_name, Class.new(Exception))
end
def error(message = nil)
self.class.error(message)
end
end
I am looking to write certain methods for processing strings, and other tasks that take place in numerous of my controllers. I know its bad practice to include helpers in your controller, so I was just wondering, where is the best place to put application wide methods used in controllers?
I realize some of you will say to put them in models, but you have to realize that not all my controllers have an associated model. Any and all input would be appreciated.
I tend to put them into helpers. The fact that they are included in views
automatically haven't been a problem for me. You can also place them into
something like app/concerns/ or lib/
I don't like cluttering ApplicationController with private methods
because this often becomes a mess.
Example:
module AuthenticationHelper
def current_user
#current_user # ||= ...
end
def authenticate!
redirect_to new_session_url unless current_user.signed_in?
end
end
module MobileSubdomain
def self.included(controller)
controller.before_filter :set_mobile_format
end
def set_mobile_format
request.format = :mobile if request.subdomain == "m"
end
end
class ApplicationController
include AuthenticationHelper
include MobileSubdomain
end
If you need to use a method in the application scope then I would suggest that you keep those methods inside the application controller and in order to use them inside views.. declare those as helper methods.
For example,
class ApplicationController < ActionController::Base
helper_method :current_user, :some_method
def current_user
#user ||= User.find_by_id(session[:user_id])
end
def some_method
end
end
I would suggest to put them in lib folder. So for example I have:
lib/utils/string_utils
module StringUtils
def foo
...
end
end
class BarController < ActionController::Base
include StringUtils
end
This demonstrates good methodology called Fat model, Thin controller, in this case we are using Mixins instead of Models to separate logic but idea is same. You want your controllers as simple as possible.
It all depends on your needs. I will provide here 2 examples. Both of them are just a custom libraries, located under lib directory.
First example - "custom string processing"
# lib/filters.rb
module Filters
# Converts value to canonical view
def self.phone(value)
# remove all non-digits
clean_value = value.gsub(/\D/, '')
country_codes = configus.phone.country_codes
area_code = configus.phone.defaults.area_code
case clean_value.length
when 7
"#{area_code}#{clean_value}"
when 11
# remove country code only if phone starts with the allowed country code
if country_codes.include?(clean_value[0].to_i)
clean_value[1..-1]
else
clean_value
end
else clean_value
end
end
# usage
# app/api/phones_controller.rb
class Api::PhonesController < Api::ApplicationController
def exists
if params[:q]
clean_value = Filters.phone(params[:q])
...
end
end
end
Second example - helper for flash messages
# lib/flash_helper.rb
module FlashHelper
def flash_translate(key, options = {})
scope = [:flash, :controllers]
scope += params[:controller].split('/')
scope << params[:action]
t(key, {:scope => scope}.merge(options))
end
end
# app/application_controller.rb
class ApplicationController < ActionController::Base
include FlashHelper
end
# usage
# app/your_controller.rb
class YourController < ApplicationController
def create
#object = Object.new(params[:object])
if #object.save
flash[:success] = flash_translate(:success)
...
end
end
end
Note: do not forget to add lib dir to the autoload paths. In config/application.rb add/modify this line config.autoload_paths += %W(#{config.root}/lib).
So for me the answer is lib directory.
Starting from Rails 4 there is a dedicated folder for it app/controllers/concerns. So you can create a module there and then include it in a specific controller(s) or in ApplicationController if you need it available throughout all your controllers.
In case those methods are used in numerous controllers, I would define them in application_controller.rb. Every controller will inherits from it and will be capable to use any method defined there