I'm trying to create a gem which exposes an ActionCable channel, but I can't get it to work.
This is my gem
# lib/my_channel.rb
class MyChannel < ActionCable::Channel::Base
def wait(data)
# logic ...
end
end
# lib/engine.rb
module MyApp
class Engine < ::Rails::Engine
isolate_namespace MyApp
end
end
I then add the gem to my main applications Gemfile, run bundle install, start up the console and run MyChannel. Which don't yield and error, meaning that the channel as been included properly.
I then add this to my main application
// application.js
var socket = "ws://localhost:3000/cable";
var cable = ActionCable.createConsumer(socket);
cable.subscriptions.create({ "channel": "MyChannel" }, {
received: function(){
// ...
}
});
But I'm getting this error
Subscription class not found ({"command"=>"subscribe", "identifier"=>"{\"channel\":\"MyChannel\"}"})
What am I missing?
This answer doesn't apply to gems, only making channels within a Rails app.
Your my_channel.rb is located in the wrong place. I'm not sure if behaviour has changed between the betas (I'm using beta3), but it should be located in app/channels/application_cable/.
I was experiencing the same issue, and realized my channel file was named inappropriately (host.rb instead of host_channel.rb). After renaming the file, it started working.
I believe the channel files are only searched for with the specific location and naming scheme (app/channels/application_cable/*_channel.rb) by default.
Related
I'm currently working on a project to enable database backed configurations in the frontend of our application. These need to be loaded after application initialization, so I created a module to load them and added a call to it in environment.rb, after Rails.application.initialize!.
The problem is that when this code is enabled, my console gets flooded with listen loop errors with bad file descriptors like:
2020-01-24 09:18:16 -0500: Listen loop error: #<Errno::EBADF: Bad file descriptor>
/Users/fionadurgin/.asdf/installs/ruby/2.6.5/lib/ruby/gems/2.6.0/gems/puma-4.3.1/lib/puma/server.rb:383:in `select'
/Users/fionadurgin/.asdf/installs/ruby/2.6.5/lib/ruby/gems/2.6.0/gems/puma-4.3.1/lib/puma/server.rb:383:in `handle_servers'
/Users/fionadurgin/.asdf/installs/ruby/2.6.5/lib/ruby/gems/2.6.0/gems/puma-4.3.1/lib/puma/server.rb:356:in `block in run'
When I disable either the call to the ConfigurationLoader or the methods I'm calling on the model, I no longer get these errors.
The rub is that I can't reproduce this issue on another machine, or in specs. I've tried on two other laptops and on one of our staging servers and they work perfectly with the ConfigurationLoader enabled.
I've tried restarting my computer, working from a freshly cloned repository, and setting all the file permissions for the application to 777. Nothing has worked so far.
Here's the ConfigurationLoader module:
module ConfigurationLoader
# Overrides client default configurations if frontend configurations exist
def self.call
Configurations::ImportRowMapping.override_configurations
rescue ActiveRecord::NoDatabaseError => e
log_no_database_error(e)
rescue ActiveRecord::StatementInvalid => e
log_statement_invalid_error(e)
rescue Mysql2::Error::ConnectionError => e
log_connection_error(e)
end
def self.log_no_database_error(error)
Rails.logger.warn(
'Could not initialize database backed configurations, database does '\
'not exist'
)
Rails.logger.warn(error.message)
end
def self.log_statement_invalid_error(error)
Rails.logger.warn(
'Could not initialize database backed configurations, table does '\
'not exist'
)
Rails.logger.warn(error.message)
end
def self.log_connection_error(error)
Rails.logger.warn(
'Could not initialize database backed configurations, could not '\
'connect to database'
)
Rails.logger.warn(error.message)
end
end
The call in environment.rb:
# Load the Rails application.
require_relative 'application'
require_relative 'configuration_loader'
# Initialize the Rails application.
Rails.application.initialize!
ConfigurationLoader.call
And the model method being called:
def self.override_configurations
return unless any?
Rails.application.client.payroll_service_file.payroll_service_file
.mappings = all.to_a
end
I'll note here that I get the errors when either the guard clause or the assignment are enabled.
Anyone have any ideas about what's going on? I'm about at my wits' end.
So I'm still not sure on the exact cause of the problem, but the solution was to move the configuration loader call out of environment.rb and into an after_initialize block in application.rb.
I understand that from the console I can run heroku restart. What I'd like to do is to have a button in my app (admin console), where pushing that button runs a heroku restart. Does anyone know how to do that and if it's possible? So the code would look something like this:
<button id="heroku_restart">Restart</button>
$("#heroku_restart").click(function() {
$.post('/restart', {}).done(function(response) {
alert(response)
})
})
class AdminsController
# this is the action mapped to the route /restart
def restart
# code for heroku restart
end
end
So per #vpibano, as of this writing, doing it with the platform-api is a breeze. Here's the action POSTed to by a button on my website:
def restart
heroku = PlatformAPI.connect_oauth(ENV["heroku_oauth_token"])
heroku.dyno.restart_all("lastmingear")
render nothing: true
end
As per the description mentioned in the post, the one way of doing it is :
1) First locate the server.pid file
pid_file = Rails.root.join("tmp", "pids", "server.opid")
2) Now, truncate the contents of the file
File.open(pid_file, "w") {|f| f.truncate(0)}
3) Finally, run the server using Kernel module:
Kernel.exec("rails s")
Note: As rightly, mentioned by #vpibano you will need authentication to access your app.
This is not a working model but a way to achieve the requirement.
Hope it helps!!
I am using a background job in order to import user data from a csv file into my datase. First I did this "hard" in my User model by simply calling a method in my User model and by passing the file path which is transmitted via a form file_field:
User.import_csv(params[:file].path)
Worked well locally and on production (heroku).
Now when it comes to huge CSV files, I understood that I need a job to perform this import in the background. I am familiar with redis and sidekiq so the job was built quickly.
CsvImportJob.perform_async(URI.parse(params[:file].path))
and in my worker:
def perform(file_path)
User.import_csv(file_path)
end
Well, that also works perfect locally but as soon as I hit this on production, I see the following error in my log:
» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987726+00:00 app worker.1 - - 3 TID-oqvt6v1d4 ERROR: Actor crashed!
» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987728+00:00 app worker.1 - - Errno::ENOENT: No such file or directory # rb_sysopen - /tmp/RackMultipart20150810-6-14u804c.csv
» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987730+00:00 app worker.1 - - /app/vendor/ruby-2.2.2/lib/ruby/2.2.0/csv.rb:1256:in `initialize'
This is meant to be the file_path variable.
Somehow heroku is not able to find the file when I pass it to a sidekiq job. When I do this without sidekiq, it works.
I don't really know how to tackle this issue so any help is appreciated.
I had the same experience, you can look at a similar project of mine at https://github.com/coderaven/datatable-exercise/tree/parallel_processing
(Basically just focus on object_record.rb model and the jobs: import_csv_job.rb and process_csv_job.rb)
The error: Errno::ENOENT: No such file or directory # rb_sysopen
If you said that this works on heroku then probably that means that the path you are getting this is valid (in your example you are using the /tmp/ path)
So here's 2 probable problems and their solution:
1.) You have saved an unknown to Heroku path (or inaccessible path) which cannot be access or opened by the application when it is running. Since, when handling the import csv without sidekiq - the file you uploaded are save temporarily in-memory until you finish processing the csv - However, in a job scheduler (or sidekiq) the path should not be in memory and should be an existing path that is accessible to the app.
Solution: Save the file to a storage somewhere (heroku has an ephemeral filesystem so you cannot save files via the running web-app) to work this around, you have to use an Amazon S3 like service (you can also use Google Drive like what I did) to save your files there and then give the path to your sidekiq worker - so it can access and process it later.
2.) If the paths are correct and the files are save or processed correctly then from my experience it could have been that you are using File.open instead of the open-uri's open method. File.open does not accept remote files, you need to require open-uri on your worker and then use the open method to work around remote files.
ex.
require 'open-uri'
class ProcessCsvJob < ActiveJob::Base
queue_as :default
def perform(csv_path)
csv_file = open(csv_path,'rb:UTF-8')
SmarterCSV.process(csv_file) do |array|
.... code here for processing ...
end
end
end
I'm fully aware this question is already past almost a year, so if you have solved this or this answer worked then it could also help serve as a documentation archive for those who will probably experience the same problem.
You can't pass a file object to the perform method.
The fix is to massage the data beforehand and pass in the parameters you need directly.
Something like...
def import_csv(file)
CSV.foreach(file.path, headers: true) do |row|
new_user = { email: row[0], password: row[1] }
CsvImportJob.perform_async(new_user)
end
end
Note: you'd call CsvImportJob.perform_later for Sidekiq with ActiveJob and Rails 5.
You got the error because on production/staging and sidekiq run on different servers.
Use my solution: upload csv to google cloud storage
class Services::Downloader
require 'fog'
StorageCredentials = YAML.load_file("#{::Rails.root}/config/g.yml")[Rails.env]
def self.download(file_name, local_path)
storage = Fog::Storage.new(
provider: "Google",
google_storage_access_key_id: StorageCredentials['key_id'],
google_storage_secret_access_key: StorageCredentials['access_key'])
storage.get_bucket(StorageCredentials['bucket'])
f = File.open(local_path)
storage.put_object(StorageCredentials['bucket'], file_name, f)
storage.get_object_https_url(StorageCredentials['bucket'], file_name, Time.now.to_f + 24.hours)
end
end
Class User
class User < ApplicationRecord
require 'csv'
require 'open-uri'
def self.import_data(file)
load_file = open(file)
data = CSV.read(load_file, { encoding: "UTF-8", headers: true, header_converters: :symbol, converters: :all})
...
Worker
class ImportWorker
include Sidekiq::Worker
sidekiq_options queue: 'workers', retry: 0
def perform(filename)
User.import_data(filename)
end
end
and code for start worker
--
path = Services::Downloader.download(zip.name, zip.path)
ImportWorker.perform_async(path)
I've installed super_exception_notifier by running:
sudo gem install super_exception_notifier
and then I've tried enabling it in my project (which already has mailing working, since it sends emails for other purposes) like this. On environment.rb I added
# Notification configuration
require 'exception_notifier'
ExceptionNotifier.configure_exception_notifier do |config|
config[:exception_recipients] = %w(info#isitsciencefiction.com)
config[:notify_error_codes] = %W( 404 405 500 503 )
end
and on my application_controller.rb I have:
require 'exception_notifiable'
class ApplicationController < ActionController::Base
include ExceptionNotifiable
Am I missing something? because no matter what error I generate. Either a 404, a route error, division by zero in a controller or in the console, in development or production mode, I get no emails and no error messages or anything at all.
Any ideas?
Pablo,
Thanks for pointing out the holes in the documentation. I will setup a blank rails project and then clearly enumerate the steps. I have already updated the Readme in response to the tickets you created on github.
To help with you immediate problem this is how I have it setup, (and it works for me! :)
Not all parts of this are essential to it working, but I'm not editing it (much), so you can see what I have:
I have this in my environment.rb:
config.load_paths += %W( #{RAILS_ROOT}/app/middlewares #{RAILS_ROOT}/app/mixins #{RAILS_ROOT}/app/classes #{RAILS_ROOT}/app/mailers #{RAILS_ROOT}/app/observers )
I have an initializer in config/initializers/super_exception_notification.rb
#The constants ($) are set in the config/environments files.
ExceptionNotifier.configure_exception_notifier do |config|
config[:render_only] = false
config[:skip_local_notification] = false
config[:view_path] = 'app/views/errors'
config[:exception_recipients] = $ERROR_MAIL_RECIPIENTS
config[:send_email_error_codes] = $ERROR_STATUS_SEND_EMAIL
#config[:sender_address] = %("RINO #{(defined?(Rails) ? Rails.env : RAILS_ENV).humanize} Error" )
config[:sender_address] = "errors#swankywebdesign.com"
config[:email_prefix] = "[RINO #{(defined?(Rails) ? Rails.env : RAILS_ENV).capitalize} ERROR] "
end
Then in my application.rb I have this:
include ExceptionNotifiable, CustomEnvironments
alias :rescue_action_locally :rescue_action_in_public if Environments.local_environments.include?(Rails.env)
self.error_layout = 'errors'
self.exception_notifiable_verbose = false
self.exception_notifiable_silent_exceptions = [MethodDisabled]
Then I also have this mixin in my app/mixins directory:
module CustomEnvironments
module Environments
def self.local_environments
%w( development test )
end
def self.deployed_environments
%w( production staging )
end
end
end
One other thing, this plugin does not abolish the rails standard which is that things in public are trump. So if you have 404.html in public, it will always get rendered for 404's.
Peter
Maybe it has has something to do with this:
http://github.com/pboling/exception_notification
Email notifications will only occur when the IP address is determined not to be local. You can specify certain addresses to always be local so that you’ll get a detailed error instead of the generic error page. You do this in your controller (or even per-controller).
consider_local "64.72.18.143", "14.17.21.25"
You can specify subnet masks as well, so that all matching addresses are considered local:
consider_local "64.72.18.143/24"
The address "127.0.0.1" is always considered local. If you want to completely reset the list of all addresses (for instance, if you wanted "127.0.0.1" to NOT be considered local), you can simply do, somewhere in your controller:
local_addresses.clear
I want to use cache-money but I don't want to start automatically caching everything (I'm working with a large production app, terabytes of data etc). How do I use it for only the models that I specify? Right now I've got:
# initializers/cache_money.rb
require 'cache_money'
config = (cfg = YAML.load(IO.read(File.join(RAILS_ROOT, "config", "memcached.yml"))))[RAILS_ENV] || cfg["defaults"]
$memcache = MemCache.new(config)
$memcache.servers = config['servers']
$local = Cash::Local.new($memcache)
$lock = Cash::Lock.new($memcache)
$cache = Cash::Transactional.new($local, $lock)
and then in the model I want to cache with cache-money:
# my_model.rb
class MyModel < ActiveRecord::Base
is_cached :repository => $cache
# ...
end
But this doesn't work; the call to is_cached gives the following error: NoMethodError: undefined method `create' for Config:Module
Any ideas? Failing that, is there anywhere I can go for help with cache-money? I couldn't find a mailing list or anything.
I think this is a bug in the cache_money code.
There are forks available on github that fix this bug, eg:
http://github.com/quake/cache-money
The fix can be seen with this commit:
http://github.com/quake/cache-money/commit/54c3d12789f31f2904d1fe85c102d7dbe5829590
I've just experienced the same problem trying to deploy an application. Running on my development machine it was fine, but it failed with this error on the production machine.
Apart from the architecture (OSX vs CentOS) the only difference i could see was that the ruby versions were different (1.8.6 p114 vs 1.8.6 p0). After upgrading the server to the latest 1.8 version (1.8.7 p160) this error went away.