Polling in ES6 and Rails - ruby-on-rails

What I'm doing: I'm trying to make a simple polling mechanism with ES6.
Optimally, it should refresh a partial on index page every 5 seconds.
It doesn't work. Logs write that the template was rendered, but nothing happens in browser.
app/javascript/packs/polls.js.erb:
var sleep = time => new Promise(resolve => setTimeout(resolve, time))
var poll = (promiseFn, time) => promiseFn().then(
sleep(time).then(() => poll(promiseFn, time)))
poll(() => new Promise(() => {
fetch('/shows/refresh_results', {
method: 'GET'
})//.then(response => {
// document.getElementById('top-shows-table-container').innerHTML = ("<%= j render partial: 'shows/top_shows_table' %>");
// })
}), 5000)
app/controllers/application_controller.rb:
class ShowsController < ApplicationController
def index
#shows = Shows::OrderedByAverageReviewsScoreQuery.new.call
end
def refresh_results
#shows = Shows::OrderedByAverageReviewsScoreQuery.new.call
respond_to do |format|
format.js
end
# render :index # this one doesn't work either
end
end
app/views/shows/refresh_results.js.erb:
$('#top-shows-table-container').html("<%= render 'top_shows_table' %>");
CommentPoller.poll();
According to logs, the last file gets called. But nothing happens to page in browser.
Started GET "/shows/refresh_results" for 127.0.0.1 at 2018-12-05 03:06:06 +0300
Processing by ShowsController#refresh_results as */*
Rendering shows/refresh_results.js.erb
Rendered shows/refresh_results.js.erb (0.5ms)
Completed 200 OK in 6ms (Views: 3.6ms | ActiveRecord: 0.0ms)
I also tried inserting .erb code directly into .polls.js, which didn't work either. It is currently commented out. If I do uncomment it, it will produce this error:
ERROR in ./app/javascript/packs/polls.js.erb
Module build failed: Error: rails-erb-loader failed with code: 1
at ChildProcess.<anonymous> (/home/.../projects/leaderboard-challenge/node_modules/rails-erb-loader/index.js:125:16)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:920:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:230:5)

Related

Server replies with default debug response instead of raised exception response

Within an engine w/ an API, when querying the API an exception is thrown, but the server response is not using the response specified, and instead rendering a default debug response (in production).
I can confirm that the exception is caught by the controller:
Started GET "/api_v2/admin/submissions?system_id=123&spt_id=123" for
127.0.0.1 at 2019-03-15 10:04:37 -0400
Processing by ApiV2::Admin::SubmissionsController#show as JSON
Parameters: {"system_id"=>"123", "spt_id"=>"123"}
[3, 12] in /....../emp_api_v2/app/controllers/emp_api_v2/application_controller.rb
3:
4: before_action :doorkeeper_authorize!
5:
6: rescue_from ::ActiveRecord::RecordNotFound do |e|
7: byebug
=> 8: response(:standard_error, 500, "Hello World")
9: end
10:
11: def doorkeeper_unauthorized_render_options(error: nil)
12: { json: { message: "Not authorized" }, status: 403 }
(byebug) cont
Completed 500 Internal Server Error in 5220ms (ActiveRecord: 0.0ms)
ActiveRecord::RecordNotFound - Couldn't find Emp::System with 'id'=123:
The server is expected to respond with 500 Server Error not the debug error stacktrace.
Why are there two responses, even though the controller catches the exception and runs a response method.
NOTE: This happens in dev and prod ! Server responds with 500 first (my catch response) but then with a stacktrace and 404 (As this is the source of the error and correct exception). It breaks my tests as the past response was 500. I was not able to revert my server to the old behavior by: reinstalling ruby, reinstalling rails + all gems + rolling back all changes throughout the repo. This behavior seems to be externally set by a ENV variable or something else.
I'd be grateful for any insight.
Edit: The (api) app controller looks like this:
module ApiV2
class ApplicationController < ActionController::API
before_action :doorkeeper_authorize!
rescue_from ::ActiveRecord::RecordNotFound do |e|
response(:standard_error, 500, "Hello World")
end
def doorkeeper_unauthorized_render_options(error: nil)
{ json: { message: "Not authorized" }, status: 403 }
end
end
end
Edit 2: I was able to get the correct response by wrapping the call in a rescue block. That code will result in a lot of begin/rescue blocks though as each of them has a specific error message.
begin
system = Emp::System.find(sys_id)
rescue
render json: { status: 500, content: "Specific Error msg" } and return
end
Originally i had a method as follows:
def handle_exception(message, &block)
begin
block.call
rescue Exception => e
render json: { message: message }, status: 500 and return
end
end
This will result in double render error as it's not returning from the top-level method but from the block.

Getting rails error when using Spaceship::Tunes

In a rails app I am running:
54 def itunes_all_apps
55 begin
56 Spaceship::Tunes.login(params[:itunes_username], params[:itunes_password])
57 apps = Spaceship::Tunes::Application.all
58 render json: apps.to_json, status: 200
59 rescue => e
60 render json: {error: e}.to_json, status: 500
61 end
62 end
It returns a status 500 error with no other information every time.
However, if I change this around slightly, for example getting teams (note, from Spaceship, not Spaceship::Tunes) this works fine:
def itunes_all_apps
begin
spaceship = Spaceship.login(params[:itunes_username], params[:itunes_password])
teams = spaceship.teams
render json: teams.to_json, status: 200
rescue => e
render json: {error: e}.to_json, status: 500
end
end
I'm not using any fast file or or config or anything. Just passing in a username and password via an api call and trying to get a response back. I'm new to rails so it may be my implementation of the Spaceship examples provided.
Using spaceship 0.36.1 gem (the latest)
I've pored through the docs to no avail. Grasping for any leads on what I'm doing wrong.
http://www.rubydoc.info/gems/spaceship/Spaceship/Tunes
https://github.com/fastlane/fastlane/blob/master/spaceship/docs/iTunesConnect.md
Someone suggested I run these two commands in irb, which I did, and they worked perfect!
Spaceship::Tunes.login('myAppleId', 'myPassword')
Spaceship::Tunes::Application.all
So it's not an iTunes account problem or credentials problem (because it works in irb), routes problem (because I ran both rails methods above with same route), or params problem (because I ran both rails methods above with same param names).
I really appreciate any suggestions. Thanks.
Edit:
Commenting out begin, rescue, and rending the error, the stack trace is as follows:
2016-10-24T17:47:34.974650+00:00 app[web.1]: Started POST "/api/v1/users/13/itunes_all_apps" for 162.237.102.13 at 2016-10-24 17:47:34 +0000
2016-10-24T17:47:34.977478+00:00 app[web.1]: Processing by Api::V1::UsersController#itunes_all_apps as JSON
2016-10-24T17:47:34.977521+00:00 app[web.1]: Parameters: {"itunes_username"=>"myCorrectUsername", "itunes_password"=>"[FILTERED]", "team_id"=>"myCorrectTeamId", "id"=>"13", "user"=>{}}
2016-10-24T17:47:35.629629+00:00 heroku[router]: at=info method=POST path="/api/v1/users/13/itunes_all_apps" host=myHerokuApp.herokuapp.com request_id=002d906d-354e-4633-8b54-71aa5181e3a7 fwd="161.237.102.13" dyno=web.1 connect=2ms service=657ms status=500 bytes=259
2016-10-24T17:47:35.619597+00:00 app[web.1]: Completed 500 Internal Server Error in 642ms (ActiveRecord: 0.0ms)
2016-10-24T17:47:35.620430+00:00 app[web.1]:
2016-10-24T17:47:35.620432+00:00 app[web.1]: IOError (not opened for reading):
2016-10-24T17:47:35.620434+00:00 app[web.1]:
2016-10-24T17:47:35.620433+00:00 app[web.1]: app/controllers/api/v1/users_controller.rb:58:in `itunes_all_apps'
It seems that Spaceship::Fastlane::Application does not implement as_json method and the default as_json touches some IO object, which cannot be represented as json.
My suggestion would be to create JSON serializer. You could use active_model-serializer, but if you do not want to create a dependency just for one object, then you can create your own serializer.
class SpaceshipApplicationSerializer
attr_reader :spaceship_applications
def initialize(spaceship_applications)
#spaceship_applications = spaceship_applications
end
def as_json(options = {})
spaceship_applications.each_with_object([]) do |spaceship_application, memo|
memo << object_as_json(spaceship_application)
end
end
def object_as_json(object)
attributes.each_with_object({}) do |attribute, memo|
memo[attribute] = object.send(attribute)
end
end
def attributes
[
:apple_id,
:name,
:vendor_id,
:bundle_id,
:last_modified,
:issues_count,
:app_icon_preview_url
]
end
end
# In your controller
def itunes_all_apps
begin
Spaceship::Tunes.login(params[:itunes_username], params[:itunes_password])
apps = Spaceship::Tunes::Application.all
render json: SpaceshipApplicationSerializer.new(apps).to_json, status: 200
rescue => e
render json: {error: e}.to_json, status: 500
end
end
EDIT:
Yes, the classes return an array, but the actual objects in array don't play nicely with json. It's hard to say if the problem is with the library - on one hand Spaceship::Tunes::Application not returning a proper json representation is a missing feature, but if the to_json raises an exception (a method the class responds to) - then I would say that is a bug.
Creating your own serializer to build json representation the way you want it - is a common pattern.

Why am I getting "Error 404 not found" in Ruby on Rails?

This is my issue: When I run the command rails server and go to localhost:3000 I get the page "Error 404 not found", so I try to put localhost:3000/home because it is a view but the issues continue. This is the log in the CMD..
C:\Sites\ifurniture>rails s
=> Booting WEBrick
=> Rails 4.2.7.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2016-08-16 12:45:45] INFO WEBrick 1.3.1
[2016-08-16 12:45:45] INFO ruby 2.2.4 (2015-12-16) [i386-mingw32]
[2016-08-16 12:45:45] INFO WEBrick::HTTPServer#start: pid=192 port=3000
Started GET "/" for ::1 at 2016-08-16 12:45:47 -0500
ActiveRecord::SchemaMigration Load (1.0ms) SELECT "schema_migrations".* FROM
"schema_migrations"
Processing by Refinery::PagesController#home as HTML
Parameters: {"locale"=>:es}
Refinery::Page Load (1.0ms) SELECT "refinery_pages".* FROM "refinery_pages"
WHERE "refinery_pages"."link_url" = ? LIMIT 1 [["link_url", "/"]]
Refinery::Page Load (7.0ms) SELECT "refinery_pages".* FROM "refinery_pages"
WHERE "refinery_pages"."menu_match" = ? ORDER BY "refinery_pages"."id" ASC LIMI
T 1 [["menu_match", "^/404$"]]
Rendered public/404.html (14.0ms)
Filter chain halted as :find_page rendered or redirected
Completed 404 Not Found in 1974ms (Views: 1775.1ms | ActiveRecord: 11.0ms)
Started GET "/home" for ::1 at 2016-08-16 12:46:00 -0500
Processing by Refinery::PagesController#show as HTML
Parameters: {"path"=>"home", "locale"=>:es}
Refinery::Page Load (29.0ms) SELECT "refinery_pages".* FROM "refinery_pages"
INNER JOIN "refinery_page_translations" ON "refinery_page_translations"."refine
ry_page_id" = "refinery_pages"."id" WHERE "refinery_pages"."parent_id" IS NULL A
ND "refinery_page_translations"."locale" IN ('es', 'en') AND "refinery_page_tran
slations"."slug" = 'home' ORDER BY "refinery_pages"."id" ASC LIMIT 1
Refinery::Page Load (0.0ms) SELECT "refinery_pages".* FROM "refinery_pages"
WHERE "refinery_pages"."menu_match" = ? ORDER BY "refinery_pages"."id" ASC LIMI
T 1 [["menu_match", "^/404$"]]
Rendered public/404.html (0.0ms)
Filter chain halted as :find_page rendered or redirected
Completed 404 Not Found in 1475ms (Views: 1207.8ms | ActiveRecord: 29.0ms)
[2016-08-16 12:46:07] INFO going to shutdown ...
[2016-08-16 12:46:07] INFO WEBrick::HTTPServer#start done.
Exiting
This is my routes file..
Rails.application.routes.draw do
# This line mounts Refinery's routes at the root of your application.
# This means, any requests to the root URL of your application will go to Refinery::PagesController#home.
# If you would like to change where this extension is mounted, simply change the
# configuration option `mounted_path` to something different in config/initializers/refinery/core.rb
#
# We ask that you don't use the :as option here, as Refinery relies on it being the default of "refinery"
post '/suscribir' => 'subscribe#create'
mount Refinery::Core::Engine, at: Refinery::Core.mounted_path
end
The pages_Controller.rb code..
module Refinery
class PagesController < ::ApplicationController
include Pages::RenderOptions
include Productos
before_action :find_page, :set_canonical
before_action :error_404, :unless => :current_user_can_view_page?
# Save whole Page after delivery
after_action :write_cache?
# This action is usually accessed with the root path, normally '/'
def home
#posts = Blog::Post.newest_first.live.includes(:comments, :categories)
render_with_templates?
end
# This action can be accessed normally, or as nested pages.
# Assuming a page named "mission" that is a child of "about",
# you can access the pages with the following URLs:
#
# GET /pages/about
# GET /about
#
# GET /pages/mission
# GET /about/mission
#
def show
#productos = Refinery::Productos::Producto.all
if should_skip_to_first_child?
redirect_to refinery.url_for(first_live_child.url) and return
elsif page.link_url.present?
redirect_to page.link_url and return
elsif should_redirect_to_friendly_url?
redirect_to refinery.url_for(page.url), :status => 301 and return
end
render_with_templates?
end
protected
def requested_friendly_id
if ::Refinery::Pages.scope_slug_by_parent
# Pick out last path component, or id if present
"#{params[:path]}/#{params[:id]}".split('/').last
else
# Remove leading and trailing slashes in path, but leave internal
# ones for global slug scoping
params[:path].to_s.gsub(%r{\A/+}, '').presence || params[:id]
end
end
def should_skip_to_first_child?
page.skip_to_first_child && first_live_child
end
def should_redirect_to_friendly_url?
requested_friendly_id != page.friendly_id || (
::Refinery::Pages.scope_slug_by_parent &&
params[:path].present? && params[:path].match(page.root.slug).nil?
)
end
def current_user_can_view_page?
page.live? || authorisation_manager.allow?(:plugin, "refinery_pages")
end
def first_live_child
page.children.order('lft ASC').live.first
end
def find_page(fallback_to_404 = true)
#page ||= case action_name
when "home"
Refinery::Page.find_by(link_url: '/')
when "show"
Refinery::Page.friendly.find_by_path_or_id(params[:path], params[:id])
end
#page || (error_404 if fallback_to_404)
end
alias_method :page, :find_page
def set_canonical
#canonical = refinery.url_for #page.canonical if #page.present?
end
def write_cache?
# Don't cache the page with the site bar showing.
if Refinery::Pages.cache_pages_full && !authorisation_manager.allow?(:read, :site_bar)
cache_page(response.body, File.join('', 'refinery', 'cache', 'pages', request.path).to_s)
end
end
end
end
When I try to deploy all to Heroku, my app crashes and I get "Application Error".... Please help me, I'm a newbie with Ruby on Rails, thanks.
#iFurniture, problem is here, your 'fallback_to_404' is set to true,
so you get always error_404
def find_page(fallback_to_404 = true)
#page ||= ...
#page || (error_404 if fallback_to_404)
end
I suggest you do it like this:
def find_page(fallback_to_404: false)
error_404 if fallback_to_404
#page ||= ...
#page || (error_404 if fallback_to_404)
end
So fallback_to_404 will be false by default and if you want to set it true, just call it like that
find_page(fallback_to_404: true)
Ruby 2 Keyword Arguments
About this:
#page || (error_404 if fallback_to_404)
May be you want ?
fallback_to_404 ? error_404 : #page
Look a litle better.
I would check your before_action :error_404, :unless => :current_user_can_view_page? Maybe remove that code for the time being to see if it can load up, if it does then there is a good chance that the method is set up incorrectly.
i can resolve the issue just running the CMD
bundle exec rake db:seed
thanks for your help.

Problem with Rails 3 and AMF , rails3-amf, RocketAMF

im trying to get AMF to work with Rails3.
I have succesfully installed rails3-amf-0.1.0 gem and the RocketAMF-0.2.1 gem.
In my app there is a controller with the following code:
def getRandomCards
#incoming = params[0]
#cards = Cardvo.first
respond_with(#cards) do |format|
format.amf { render :amf => #cards.to_amf}
end
end
through a call from Actionscript i would like to return some data in amf format.
further more, as mentioned in the instructions for rails3-amf i did the following.
in my production.rb under config/environment i added the line
config.rails3amf.map_params :controller => 'CardvosController', :action => 'getRandomCards'
an my amf gateway got
config.rails3amf.gateway_path = "/gateway"
The problem is:
Any call from Actionscript / Flash raises the following
(taken from the log )
Started POST "/gateway" for 192.178.168.1 at Fri Nov 19 15:13:28 +0100 2010
Processing by CardvosController#getRandomCards as AMF
Parameters: {0=>100.0}
[1m[36mSQL (0.4ms)[0m [1mSHOW TABLES[0m
[1m[35mCardvo Load (0.2ms)[0m SELECT `cardvos`.* FROM `cardvos` LIMIT 1
Completed 200 OK in 13ms (Views: 0.9ms | ActiveRecord: 0.5ms)
NoMethodError (undefined method `constructed?' for #<RocketAMF::Envelope:0x39ba868>):
The Amf file is created but the method, which is in remoting.rb from RocketAMF could not be found.
I think the error is thrown at request_parser.rb from Rails3AMF asking for constructed?
# Wrap request and response
env['rack.input'].rewind
env['rails3amf.request'] = RocketAMF::Envelope.new.populate_from_stream(env['rack.input'].read)
env['rails3amf.response'] = RocketAMF::Envelope.new
# Pass up the chain to the request processor, or whatever is layered in between
result = #app.call(env)
# Calculate length and return response
if env['rails3amf.response'].constructed?
For me it seems it is looking at the wron class for the method.
Where
NoMethodError (undefined method `constructed?' for #RocketAMF::Envelope:0x39ba868):
the essential part is
RocketAMF::Envelope:0x39ba868
which should be
RocketAMF:ANOTHER_CLASS:Envelope:0x39ba868
Am i right and where the heck is the error ?
Any help would be appreciated!
chris

Error during failsafe response: Ruby on Rails 3

I have a form_tag that works fine using html, but when I use ajax with the remote => true I am getting this error:-
My terminal log shows:-
Started GET "/" for 127.0.0.1 at 2010-11-01 01:19:49 +0000
Processing by HomepagesController#index as HTML
Homepage Load (0.6ms) SELECT "homepages".* FROM "homepages"
Rendered homepages/index.html.erb within layouts/application (23.0ms)
Completed 200 OK in 40ms (Views: 27.3ms | ActiveRecord: 0.6ms)
Error during failsafe response: incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string)
* then a load of cleaner.rb stuff
then:-
Started GET "/homepages?utf8=%E2%9C%93&search=hom" for 127.0.0.1 at 2010-11-01 01:19:56 +0000
Processing by HomepagesController#index as JS
Parameters: {"utf8"=>"✓", "search"=>"hom"}
Homepage Load (0.5ms) SELECT "homepages".* FROM "homepages" WHERE (section LIKE '%hom%')
Rendered homepages/index.js.erb (2.9ms)
Completed in 19ms
In my index.js.erb I have:-
$("testsearch").update("<%= escape_javascript(render(#homepages))%>");
and in my Controller I have:-
def index
#homepages = Homepage.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #homepages }
format.js { render :layout => false }
end
in my view I have:-
which prints #homepages using a table using <% #homepages.each do |homepage| %> which is not being updated.
Anyone have any ideas as to why I get this error.
I have cracked it by going onto an IRC chat room (irc.freenode.net RubyonRails) and a ProjectZen (human being somewhere out there in the ether) helped me to get it working.
Apparently what was happening was that I was following Ryan Bates who does many extremely good Railcast videos, but he builds on previous Railcast. Therefore in his 205 Railscast, which deals with Ajax calls, he did not mention that you must have:-
format.js in the action in the controller.
His xxxx.searchxxxxx needs to be created in the controller or model.
And that when I did :-
<%= render(#homepages)%> <!-- (in his case <%= render(#products)%>) -->
The render was looking for a partial called "_homepage" (not "homepages") (I did not even have a partial therefore I got the UTF8 to ASCII error).
And then in "_homepage" I would add my code to render the results.
What I have now done in my index.html.erb is to put <%= render(#homepages)%>, in the (div id = testsearch) in place of the code I use to render #homepages and then place that code in a partial "_homepage". Now I can use "_homepage" for the html and the Ajax call.
At the moment I have a slight problem in that it is rendering all the data in the"#homepages" as many times as the number of records. At the moment I do not know why, but at least the Ajax call is working.

Resources