ActionView::Template::Error (undefined method `tr' for nil:NilClass - ruby-on-rails

I am testing out the service-worker rails gem and am using VAPID private and public keys to send push notifications. I've succesfully been able to create push notifications locally, but when I deploy to heroku, the app raises the error stated above when trying to go to the push notification page. Here is the error:
75] Started GET "/push-simple/" for 69.253.120.203 at 2017-02-12 06:37:35 +0000
2017-02-12T06:37:35.339318+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] ActionView::Template::Error (undefined method `tr' for nil:NilClass
2017-02-12T06:37:35.333379+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] Rendering pages/push-simple.html.erb within layouts/application
2017-02-12T06:37:35.332337+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] Processing by PagesController#show as HTML
2017-02-12T06:37:35.336377+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] Rendered pages/push-simple.html.erb within layouts/application (2.8ms)
2017-02-12T06:37:35.336998+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] Completed 500 Internal Server Error in 4ms
2017-02-12T06:37:35.339281+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75]
2017-02-12T06:37:35.339490+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 13: <script type="text/javascript">
2017-02-12T06:37:35.339320+00:00 app[web.1]: Did you mean? try):
2017-02-12T06:37:35.339489+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 11: </div>
2017-02-12T06:37:35.339489+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 12:
2017-02-12T06:37:35.339561+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] app/views/pages/push-simple.html.erb:14:in `_app_views_pages_push_simple_html_erb__2838769268823495646_39526220'
2017-02-12T06:37:35.339491+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 15: </script>
2017-02-12T06:37:35.339491+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 14: var publicKey = new Uint8Array(<%= WebpushClient.public_key_bytes %>);
2017-02-12T06:37:35.339492+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 16: <%= javascript_include_tag 'push-simple' %>
2017-02-12T06:37:35.339520+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75]
2017-02-12T06:37:35.339560+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] app/clients/webpush_client.rb:7:in `public_key_bytes'
And here is my webpushclient where the VAPID keys are defined:
class WebpushClient
def self.public_key
ENV['VAPID_PUBLIC_KEY']
end
def self.public_key_bytes
Base64.urlsafe_decode64(public_key).bytes
end
def self.private_key
ENV['VAPID_PRIVATE_KEY']
end
# Send webpush message using subscription parameters
#
# #param message [String] text to encrypt
# #param subscription_params [Hash<Symbol, String>]
# #option subscription_params [String] :endpoint url to send encrypted message
# #option subscription_params [Hash<Symbol, String>] :keys auth keys to send with message for decryption
# #return true/false
def send_notification(message, endpoint: "", p256dh: "", auth: "")
raise ArgumentError, ":endpoint param is required" if endpoint.blank?
raise ArgumentError, "subscription :keys are missing" if p256dh.blank? || auth.blank?
Rails.logger.info("Sending WebPush notification...............")
Rails.logger.info("message: #{message}")
Rails.logger.info("endpoint: #{endpoint}")
Rails.logger.info("p256dh: #{p256dh}")
Rails.logger.info("auth: #{auth}")
Webpush.payload_send \
message: message,
endpoint: endpoint,
p256dh: p256dh,
auth: auth,
vapid: {
subject: "jon.corrin#gmail.com",
public_key: public_key,
private_key: private_key
}
end
def public_key
self.class.public_key
end
def private_key
self.class.private_key
end
end
and here is the script im using to call the public key:
<script type="text/javascript">
var publicKey = new Uint8Array(<%= WebpushClient.public_key_bytes %>);
</script>
<%= javascript_include_tag 'push-react' %>
Like I said before, it works locally. I think I may have forgotten to define a variable, I've looked at similar posts and have been debugging for quite some time, but have had no luck. Any suggestions? I also want to add, I'm quite new, so if it's an obvious error, I'll completely understand.

Your error is coming from this method:
def self.public_key_bytes
Base64.urlsafe_decode64(public_key).bytes
end
Looking up the source code for Base64#urlsafe_decode64, this is defined by:
def urlsafe_decode64(str)
strict_decode64(str.tr("-_", "+/"))
end
This is where your undefined method 'tr' for nil:NilClass must be coming from: the public_key. Which you have defined by:
def self.public_key
ENV['VAPID_PUBLIC_KEY']
end
...In other words, you have not set the environmental variable on your production server. That's why it works locally, but not on production.

Related

redmine upgrade to 3.4.4 not working [ActionView::Template::Error (undefined method `default_users_time_zone')]

Every thing worked fine for me with Redmine 3.3. Now I wanted to upgrade to 3.4.4 and Redmine is no longer running. I searched the internet but did not find the exact same problem. Similar problems where caused by plugins but I do not have any plugins installed. I use the Passenger Docker image of Redmine.
The logs give me the following error message:
Processing by WelcomeController#index as HTML
Current user: anonymous
Redirected to http://0.0.0.0/login?back_url=http%3A%2F%2F0.0.0.0%2F
Filter chain halted as :check_if_login_required rendered or redirected
Completed 302 Found in 60ms (ActiveRecord: 3.7ms)
App 179 stdout:
Started GET "/login?back_url=https%3A%2F%2Fredmine.mydomain.tld%2F" for 95.90.204.176 at 2018-03-14 19:10:26 +0000
Processing by AccountController#login as HTML
Parameters: {"back_url"=>"https://redmine.mydomain.tld/"}
Current user: anonymous
Rendered account/login.html.erb within layouts/base (24.1ms)
Completed 500 Internal Server Error in 219ms (ActiveRecord: 4.3ms)
ActionView::Template::Error (undefined method `default_users_time_zone' for #<Class:0x00000000055f2120>
Did you mean? default_users_hide_mail):
11: <%= favicon %>
12: <%= stylesheet_link_tag 'jquery/jquery-ui-1.11.0', 'application', 'responsive', :media => 'all' %>
13: <%= stylesheet_link_tag 'rtl', :media => 'all' if l(:direction) == 'rtl' %>
14: <%= javascript_heads %>
15: <%= heads_for_theme %>
16: <%= call_hook :view_layouts_base_html_head %>
17: <!-- page specific tags -->
app/models/user_preference.rb:44:in `initialize'
app/models/user.rb:949:in `pref'
app/helpers/application_helper.rb:1451:in `javascript_heads'
app/views/layouts/base.html.erb:14:in `_app_views_layouts_base_html_erb__2446195152155203147_36658300'
lib/redmine/sudo_mode.rb:63:in `sudo_mode'
What could that be? I need to upgrade to 3.4 because I want to use a plugin but the plugin requires version 3.4 in use.
It was my fault! I did not copy every new settings file to my mounted config directory.

Getting ActionView::Template::Error error when trying to make Rails Ajax call

I’m using Rails 4.2.3. In my “app/controllers/user_objects_controller.rb” controller file, I have defined this method …
def find_totals
respond_to do |format|
#current_user = User.find(session["user_id"])
format.json {
#month_total = UserObject.find_total_by_user_object_month_and_year(session["user_id"], params[:object], params[:month], params[:year])
#year_total = UserObject.find_total_by_user_object_and_year(session["user_id"], params[:object], params[:year])
render :json => {:month => #monthTotal,
:year => #yearTotal }
}
end
end
I’m trying to use Ajax to invoke this method, and so in my “./app/assets/javascripts/user_objects.js.coffee” script, I have
updateTotal = (arg) ->
object = $('#user_object_object').val()
date = $("#datepicker").datepicker('getDate')
day = $('#user_object_day').val()
month = date.getMonth() + 1
year = date.getFullYear()
if (object != "" && day != "")
# Populate the month and year totals
$.ajax
url: "/user_objects/find_totals"
type: 'GET'
data: {month: month, year: year, object: object}
success: (data) ->
alert(data);
$('#month_total').val(data)
$('#year_total').val(data)
error: ->
alert "Something went wrong getting month and year total"
but I always get the error condition. In my Rails server the below log is printed:
D, [2016-02-24T15:42:24.475092 #12929] DEBUG -- :
D, [2016-02-24T15:42:24.475206 #12929] DEBUG -- :
D, [2016-02-24T15:42:24.475236 #12929] DEBUG -- :
D, [2016-02-24T15:42:24.475265 #12929] DEBUG -- :
I, [2016-02-24T15:42:24.475505 #12929] INFO -- : Started GET "/user_objects/find_totals?month=2&year=2016&object=3" for 127.0.0.1 at 2016-02-24 15:42:24 -0600
I, [2016-02-24T15:42:24.475539 #12929] INFO -- : Started GET "/user_objects/find_totals?month=2&year=2016&object=3" for 127.0.0.1 at 2016-02-24 15:42:24 -0600
F, [2016-02-24T15:42:24.500710 #12929] FATAL -- :
ActionView::Template::Error (undefined method `object' for nil:NilClass):
2:
3: <p>
4: <strong>object:</strong>
5: <%= #user_object.object %>
6: </p>
7:
8: <p>
app/views/user_objects/show.html.erb:5:in `_app_views_user_objects_show_html_erb__2677150194333288712_70363943163180'
F, [2016-02-24T15:42:24.500751 #12929] FATAL -- :
ActionView::Template::Error (undefined method `object' for nil:NilClass):
2:
3: <p>
4: <strong>object:</strong>
5: <%= #user_object.object %>
6: </p>
7:
8: <p>
app/views/user_objects/show.html.erb:5:in `_app_views_user_objects_show_html_erb__2677150194333288712_70363943163180'
Anyone know what this error means and how I can fix it?
It looks like Rails is trying to render show.html.erb, which implies that the ajax request is hitting the show action on your UserObjects controller, which would be indicative of incorrect routes.
Check your routes file. Routes are matched in the order they're specified, so if you have resources :user_objects before you have something like get "user_objects/find_totals" ... then Rails will think the "user_objects/find_totals" URL matches to the show action on your UserObjects controller, with an id of find_totals.
undefined method `object' for nil:NilClass
means that #user_object here
<%= #user_object.object %>
is nil. Which makes sense given that #user_object is no where to be found in your controller method/action def find_totals
You will need to set that instance variable somewhere in your controller for it to be available for you in your view
#user_object is nil.
undefined method `object' for nil:NilClass

Webhook returning 401 in Rails

I have created a webhook using Fluidsurveys which corresponds to this controller:
class HooksController < ApplicationController
skip_before_filter :verify_authenticity_token
def response_created_callback
# If the body contains the score parameter...
if params[:_completed].present?
# Create a new Response object based on the received parameters...
response = FluidsurveysResponse.new(:completed => params[:_completed])
response.invite_email = params[:_invite_email]
response.locale = params[:_locale]
response.key = params[:_key]
response.webhook = params[:webhook]
response.survey_name = params[:survey_name]
response.username = params[:_username]
response.weighted_score = params[:_weighted_score]
response.completion_time = params[:_completion_time]
response.ip_address = params[:_ip_address]
response.num_responses = params[:num_responses]
response.survey_id = params[:survey_id]
response.invite_name = params[:_invite_name]
response.language = params[:_language]
response.referrer = params[:_referrer]
response.fs_created_at = params[:_created_at]
response.fs_updated_at = params[:_updated_at]
response.survey_url = params[:survey_url]
response.fs_id = params[:_id]
response.collector_id = params[:_collector_id]
response.comment = params[:Comment]
response.nps_score = params[:NPSScore]
response.save!
end
# The webhook doesn't require a response but let's make sure
# we don't send anything
render :nothing => true
end
end
The webhook seems to work fine, as I see this in my logs:
2014-01-20T13:49:01.231772+00:00 app[web.1]: Started POST "/hooks/response_created_callback" for 184.107.171.218 at 2014-01-20 13:49:01 +0000
2014-01-20T13:49:01.327989+00:00 app[web.1]: Processing by HooksController#response_created_callback as */*
2014-01-20T13:49:01.328149+00:00 app[web.1]: Parameters: {"_invite_email"=>"N/A", "_locale"=>"298", "_updated_at"=>"2014-01-20 13:49:00.738850", "_language"=>"en", "_key"=>"b5ec09680a4274cec0052d4049bec338a906e5b8", "webhook"=>"event", "survey_name"=>"Test", "_referrer"=>"http://fluidsurveys.com/surveys/marketing/test-nps-for-dc/", "_username"=>"marketing", "survey_url"=>"http://fluidsurveys.com/surveys/marketing/test-nps-for-dc/", "_id"=>"39164209", "_created_at"=>"2014-01-20 13:49:00.243640", "_weighted_score"=>"0.0", "_completion_time"=>"00:00:00", "_completed"=>"1", "_ip_address"=>"66.192.31.1", "yptmAoJw6i"=>"Detractor: 0", "num_responses"=>"261", "survey_id"=>"263692", "_extra_info"=>"weighted_score", "_invite_name"=>"N/A"}
2014-01-20T13:49:01.369963+00:00 app[web.1]: Completed 401 Unauthorized in 41ms
As you can see, the post gets made to the right controller action. The route is setup correctly, but I get a 401 error. I don't understand what authentication needs to happen here...The params are getting passed to the controller, and in my mind I see no need for my app to authenticate anything. It receives a request, does what it's told, and then it's done.
What am I missing here that is causing the 401 error?
EDIT:
After remove skip_before_filter :verify_authenticity_token from my controller, I get this error:
Can't verify CSRF token authenticity
2014-01-20T16:07:12.222512+00:00 app[web.1]: Completed 422 Unprocessable Entity in 28ms
2014-01-20T16:07:12.225905+00:00 app[web.1]:
2014-01-20T16:07:12.225905+00:00 app[web.1]: ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
The issue is that I am using devise for user authentication, and my app was blocking the post request because there were no authentication credentials being passed to my controller.
By adding this line to my controller I solved the issue:
skip_before_filter :verify_authenticity_token, :authenticate_user!

Compiling handlebar templates into Rails

As I am working to get ember running I am now failing to get my handlebar templates to load through asset pipeline.
I'm using the handlebars_assets gem, and when I hit the server I get what is below, I verified that the path is correct, but not really sure how to fix this.
When I require handlebars.runtime:
couldn't find file 'handlebars.runtime'
(in /Users/tspore/Rails/Active/tombfinder/app/assets/javascripts/app/ember_app.js:1)
Cache read: sprockets/6f42a4ba0f2b80167ce50f9f306427fa
Compiled app/ember_app.js (5ms) (pid 9791)
Cache read: sprockets/764613d8100bb6d8e6072701f79183c1
Completed 500 Internal Server Error in 141ms
ActionView::Template::Error (can't convert nil into String
(in /Users/tspore/Rails/Active/tombfinder/app/assets/javascripts/app/templates/records/index.hbs)):
26: <% end %>
27:
28:
29: <%= javascript_include_tag 'app/ember_app' %>
30: </head>
31: <body class="<%= #class %>">
32: <div id="center">
app/views/layouts/js.html.erb:29:in `_app_views_layouts_js_html_erb__854441834177334479_70351597254240'
app/controllers/js/js_controller.rb:3:in `index'
Rendered /Users/tspore/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.1.10/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.9ms)
Rendered /Users/tspore/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.1.10/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.6ms)
Rendered /Users/tspore/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.1.10/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (3.0ms)
EDIT: After using Github version, and removing the gem from the :assets - it seems to work. But now I am getting this error -
Uncaught ReferenceError: HandlebarsTemplates is not defined records_view.js:4
Uncaught Error: assertion failed: Unable to find view at path 'App.listRecordsView'
My application looks like this -
App.listRecordsView = Ember.View.extend({
templateName: HandlebarsTemplates['records/index'](context)
});
with the ember-rails gem I got the gem to compile so now I have a script called layout.js which looks like this:
Ember.TEMPLATES["app/templates/controller/layout"] = Ember.Handlebars.template(function anonymous(Handlebars, depth0, helpers, partials, data) { helpers = helpers || Ember.Handlebars.helpers; data = data || {};
var buffer = '', stack1, hashTypes, escapeExpression=this.escapeExpression;
data.buffer.push("<h1>from template</h1>\n");
stack1 = {};
hashTypes = {};
stack1 = helpers._triageMustache.call(depth0, "outlet", {hash:stack1,contexts:[depth0],types:["ID"],hashTypes:hashTypes,data:data});
data.buffer.push(escapeExpression(stack1) + "\n");
return buffer;
});
How do I call this template in the Ember App? It has no name space to say:
templateName: 'layout'

Rails strange behavior of production app running on heroku

In user model I've got attribute location of type point. Now I've got a validation code:
validates :location, :format => { :with => /\(-?\d+(?:\.\d+)?,-?\d(?:\.\d+)?\)/,
:on => :update,
:if => :location_changed? }
It works fine in console, on localhost, but on heroku it returns:
Processing by UsersController#update as / 2012-07-31T18:14:37+00:00
app[web.1]: Parameters:
{"user"=>{"location"=>"(3.545452,2.4353534)"}, "id"=>"self"}
2012-07-31T18:14:37+00:00 app[web.1]: Completed 500 Internal Server
Error in 13ms 2012-07-31T18:14:37+00:00 app[web.1]:
2012-07-31T18:14:37+00:00 app[web.1]: NoMethodError (undefined method
location_changed?' for #<User:0x00000004dc29c8>):
2012-07-31T18:14:37+00:00 app[web.1]:
app/controllers/users_controller.rb:16:inupdate'
Actually it works also great in heroku console, but don't work in curl request.
Rails version 3.2.7.
attr_accessible :profile_picture, :password, :location
Thanks!
It looks like a magic. I fixed it with recreation if table and server restart. Very strange.

Resources