I am trying to log additional custom fields using Logstasher gem.
I need to log some response parameters, but logstasher does not support itself logging response params using configuration, therefore I put the code into after_action method in ApplicationController.
ApplicationController
after_action :set_logstasher_params
def set_logstasher_params
if LogStasher.enabled?
res_params = JSON.parse(response.body.as_json)
LogStasher.add_custom_fields do |fields|
fields[:res_params] = res_params
end
end
end
This is logstasher initializer
initializer/logstasher.rb
if LogStasher.enabled?
LogStasher.add_custom_fields do |fields|
fields[:request_params] = request.filtered_parameters
LogStasher::CustomFields.add(:myapi_runtime)
end
LogStasher.add_custom_fields_to_request_context do |fields|
fields[:request_params] = request.filtered_parameters
end
end
The problem is next:
After starting rails server, first request I send, logs only parameters which are indicated in logstasher.rb except parameters added in ApplicationController.
But After that every request logs everything indicated logstasher.rb as well as ApplicationController method.
Does anyone have idea why first time does not log response parameters from ApplicationController method?
Related
The Action Mailer Basics guide states:
You could use a before_action to populate the mail object with defaults, delivery_method_options or insert default headers and attachments.
However, I don't see how it could be possible to set delivery_method_options by doing this, as this value is only fetched from the headers argument explicitly passed to the mail method. Am I missing something, or is the documentation wrong?
The Action Mailer Basics guide was, in fact, misleading. I submitted a PR to fix the guide.
In order to define "per-mailer" delivery options, you need to use an after_action callback:
class UserMailer < ApplicationMailer
after_action :set_delivery_options
private
def set_delivery_options
# You have access to the mail instance,
# #business and #user instance variables here
if #business && #business.has_smtp_settings?
mail.delivery_method.settings.merge!(#business.smtp_settings)
end
end
end
I have controllers that look like this:
class ApplicationController < ActionController::Base
before_filter :print_params
def print_params
p params
end
end
class CommandsController < ApplicationController
before_filter :print_params
def print_params
p params
end
end
class FidelityBondRenewalsController < CommandsController
before_filter :print_params
def print_params
p params
end
def renew_with_changes
p params
end
end
When I run my cucumber tests I see print params the whole way through except for when I finally hit the renew_with_changes method and then my params disappear. I have other methods in this controller and it isn't happening to them. I've searched the code base for any differences between the other methods and this one and couldn't find anything.
If I put a binding.pry in the print_params method in the FidelityBondRenewalsController and hit next over and over again, I eventually get to:
16: def process_action(*args)
17: run_callbacks(:process_action, action_name) do
=> 18: super
19: end
20: end
which has params. If I type next, then I go to my renew_with_changes method and the params are gone.
What can I try to try to track this down? This is a Rails3.2 app, with the strong parameters gem installed to be more like Rails4, if that is useful.
Route information:
resources :fidelity_bond_renewals do
member do
.
.
.
put :renew_with_changes
end
end
The problem was two fold:
For whatever reason Binding.pry could not read the params. I haven't figured out why. I could do p params and see them. I could do a binding.pry right after that and try to p params and they would not print. This is different behavior than I described above. The only change is that I am driving today and my pair is not. We may need to resolve these difference if we can reproduce them. I'll report back on this if he experiences differences.
The params themselves were being manipulated by some code that meant that I needed to access the key differently. Once this was figured out, it all started working.
I have the following working Preview class:
class UserMailerPreview < ActionMailer::Preview
def invite
USerMailer.invite
end
end
I'm trying to pass paramaters to the method like so:
localhost:3000/rails/mailers/user_mailer/invite?key1=some_value
The server seems to receive them:
Parameters: {"key1"=>"some_value", "path"=>"user_mailer/invite"}
But when trying to access them with the hash params, I get an error.
Can I access these parameters in a Preview method and if so - how?
I dug into the code behind the mailer preview system and discovered that, unfortunately, none of the request parameters are passed to the preview class, and are thus inaccessible to the preview.
The relevant controller action is in railties: Rails::MailersControlller#preview. Here, you can see it calling ActionMailer::Preview#call and just passing the name of the "email" (ie: the appropriate method in the preview).
I hacked my way through this one today and came up with this solution and blog post on extending ActionMailer.
# config/initializers/mailer_injection.rb
# This allows `request` to be accessed from ActionMailer Previews
# And #request to be accessed from rendered view templates
# Easy to inject any other variables like current_user here as well
module MailerInjection
def inject(hash)
hash.keys.each do |key|
define_method key.to_sym do
eval " ##{key} = hash[key] "
end
end
end
end
class ActionMailer::Preview
extend MailerInjection
end
class ActionMailer::Base
extend MailerInjection
end
class ActionController::Base
before_filter :inject_request
def inject_request
ActionMailer::Preview.inject({ request: request })
ActionMailer::Base.inject({ request: request })
end
end
I am trying to access the values stored in params hash from ApplicationController class directly.How can I do it? Foreaxmple:
def setParams
#parameters=params ???
end
The univesal variable to get the ruby params is:
params
This will return the hash of parameters from the request that you can see in the server log.
To access it you just need to use:
def set_params #use ruby notation for methods which is underscore and _
#parameters=params["key"]
end
Note that the key should be defined, as long as the incoming parameters for html view includes the codification: utf8, and the csrf token.
If you want to access to the full request:
def set_params
#request = request
end
class ApplicationController < ActionController::Base
before_filter :handle_params
def handle_params
my_param_key = params[:my_param_key]
end
end
Hope this helps someone starting to code on ruby!
Basically I have a UsersInitializeController Class
class UsersInitializeController < ApplicationController
before_filter :authenticate_user!
def create
render true
end
end
authenticate_user! is found in the Application Controller
class ApplicationController < ActionController::Base
# protect_from_forgery
def authenticate_user!
#current_user = User.find_by_token params[:auth_token]
if !#current_user
#current_user = User.create :token => params[:auth_token]
end
end
end
When my application starts, it sends POST request to the UsersInitializeController. Since before_filter is set, it will thus call authenticate_user! first. However the error I got says before_filter is an undefined method.
From my knowledge, before_filter exist in ActionController, and since UsersInitializeContoller < ApplicationController < ActionController, I shouldn't be getting this error. Has anyone encounter this issue before ?
Exception Stack (as requested)
Started POST "/users_initialize.json" for 127.0.0.1 at 2012-03-06 00:32:50 -0800
ActionController::RoutingError (undefined method `before_filter' for UsersInitializeController:Class):
app/controllers/users_initialize_controller.rb:3:in `<class:UsersInitializeController>'
app/controllers/users_initialize_controller.rb:1:in `<top (required)>'
Routes.rb file (as requested)
MyApplication::Application.routes.draw do
resources :users_initialize
match 'info/required_client_version' => 'info#required_client_version'
end
### Problem Solved ###
Unused Devise Gem somehow causing the complication. Removed it and done.
add the before_filter within an "included do" block:
included do
before_filter :authenticate_user!
end
Update:
just noticed you solved it already. However I was having the same troubles and the solution above solved it in my case. So, I'll leave the comment here since it may help others
Not able to reproduce, the code you posted works fine on my Rails 3.2.2 app.
Probably there is something wrong with your source file (i.e. some extra hidden bytes somewhere).
You could try a step-by-step approach to solve this:
add a new UsersController and add resources :users to routes.rb
add an index action with the following code:
def index
render :text => "Hello there"
end
When you visit http://localhost:3000 you should see the text "Hello there"
Add the before_filter and verify that the filter is executed by adding e.g. logger.warn( 'In the Filter' ) to the beginning of the filter method