I am trying to get notifications to work in my app. I found "noticed gem" from this GitHub repo and followed all the steps that he does. I have the gem in my gem file, I did bundle install and update and rails db:migrate and everything. However when I try running this in rails console
CommentNotification.with(post: #post).deliver(current_user)
I get
Traceback (most recent call last):
1: from (irb):1
NameError (uninitialized constant CommentNotification)
This is my comment_notification.rb class that gets generated under app/notifications/comment_notificaiton.rb when I run rails generate noticed:notification CommentNotification just as he does in the video and just as the documentation suggests.
# To deliver this notification:
#
CommentNotification.with(post: #post).deliver_later(current_user)
CommentNotification.with(post: #post).deliver(current_user)
class CommentNotification < Noticed::Base
# Add your delivery methods
#
deliver_by :database
# deliver_by :email, mailer: "UserMailer"
# deliver_by :slack
# deliver_by :custom, class: "MyDeliveryMethod"
# Add required params
#
param :post
# Define helper methods to make rendering easier.
#
def message
t(".message")
end
#
def url
post_path(params[:post])
end
end
You have to restart your spring server.
Using bin/spring stop command, the spring server will be stopped. Then the server will be started using rails server or rails s.
A bit late to this, but manually loading the notification class in rails console solved this issue in my case, i.e.: load "app/notifications/comment_notification.rb". (PS: I would also check the spelling of the file name, i.e. comment_notification vs comment_notificaiton)
Uncomment the first two lines:
# CommentNotification.with(post: #post).deliver_later(current_user)
# CommentNotification.with(post: #post).deliver(current_user)
remember, #post must be the resource that you are going to store in user notifications
user.notifications
#post must exist
Related
I have plugin that takes attribute from post's front matter and uses it in permalink. Problem is I need to clean up any accents and diacritics from the string before putting it in to the permalink. Ruby on rails has method called parametrize which does exactly what I need but I have no idea how to use it in plugin.
This is plugins code I have:
module JekyllCustomPermalink
class CustomPermalink < Jekyll::Generator
safe true
priority :low
def generate(site)
# nothing to do, wait for hook
end
Jekyll::Hooks.register :documents, :pre_render do |doc|
begin
# check if jekyll can resolve the url template
doc.url
rescue NoMethodError => error
begin
if !doc.collection.metadata.fetch("custom_permalink_placeholders").is_a?(Array)
raise CustomPermalinkSetupError, "The custom placeholders need to be an array! Check the settings of your '#{doc.collection.label}' collection."
end
def doc.url_template
#custom_url_template ||= collection.metadata.fetch("custom_permalink_placeholders").inject(collection.url_template){|o,m| o.sub ":" + m, data[m].to_s.parameterize}
end
rescue KeyError
# "custom_permalink_placeholders"
raise CustomPermalinkSetupError, "No custom placeholders defined for the '#{doc.collection.label}' collection. Define an array of placeholders under the key 'custom_permalink_placeholders'. \nCaused by: " + error.to_s
end
end
end
end
end
but I get this error:
john#arch-thinkpad ~/P/blog (master)> bundle exec jekyll serve --trace
Configuration file: /home/john/Projects/lyricall/_config.yml
Source: /home/john/Projects/lyricall
Destination: /home/john/Projects/lyricall/_site
Incremental build: disabled. Enable with --incremental
Generating...
Jekyll Feed: Generating feed for posts
Liquid Exception: undefined method `parameterize' for "Žďořšťáčik":String in feed.xml
bundler: failed to load command: jekyll (/home/john/.gem/ruby/3.0.0/bin/jekyll)
/usr/lib/ruby/gems/3.0.0/gems/jekyll_custom_permalink-0.0.1/lib/jekyll_custom_permalink/custom_permalink.rb:20:in `block in url_template': undefined method `parameterize' for "Žďořšťáčik":String (NoMethodError)
What am I doing wrong ? How can I use this method which should be part of a string class but apparently it is not ? How can I achieve same result without ruby on rails framework ?
INFO:
jekyll 4.1.1
ruby 3.0.1p64 (2021-04-05 revision 0fb782ee38) [x86_64-linux]
Thank you for help
Rails additions to base Ruby classes, like String#parameterize, are part of the Active Support Core Extensions. The activesupport gem can be installed and used independent of Rails.
To keep the default footprint low, ActiveSupport allows you to require only the individual extensions you want to use. In your case, you will need to require the string inflection extensions:
require 'active_support/core_ext/string/inflections'
"Kurt Gödel".parameterize
=> "kurt-godel"
I've posted a bug for this on rmosolgo/graphql-ruby but just in case I may be doing something wrong, I'm hoping to see if anyone else has a solution to my problem.
When creating an API only rails application it seems that Rails believes the execute method in my GraphqlController is missing.
Here is my graphql_controller.rb file:
class GraphqlController < ApplicationController
# If accessing from outside this domain, nullify the session
# This allows for outside API access while preventing CSRF attacks,
# but you'll have to authenticate your user separately
protect_from_forgery with: :null_session
def execute
variables = ensure_hash(params[:variables])
query = params[:query]
operation_name = params[:operationName]
context = {
# Query context goes here, for example:
# current_user: current_user,
}
result = RailsApiGraphqlExecuteTestSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
render json: result
rescue => e
raise e unless Rails.env.development?
handle_error_in_development e
end
# ... continues on
end
Here is my routes.rb file:
Rails.application.routes.draw do
post "/graphql", to: "graphql#execute"
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
when I run rake routes this is what I get:
prompt> rake routes
Prefix Verb URI Pattern Controller#Action
graphql POST /graphql(.:format) graphql#execute
... continues on
You should be able to reproduce this with the following command line steps:
rails new execute-test --api
cd execute-test
vim Gemfile # or open an editor and add "gem 'graphql'"
bundle
rake db:create
rails g graphql:install
rake routes # to test that the route exists
rails s
When you use an app like GraphiQL and go to http://localhost:3000/graphql you'll get the following error:
Started POST "/graphql" for 127.0.0.1 at 2019-10-15 16:23:29 -0700
(0.3ms) SELECT sqlite_version(*)
AbstractController::ActionNotFound (The action 'execute' could not be found for GraphqlController):
... strack trace continues ...
Maybe I'm doing something wrong? Any help would be much appreciated.
It looks like this line in the execute method:
protect_from_forgery with: :null_session
is what caused the problem. I'll have to look into this some more. +1 and I'll even mark the answer correct if someone can figure out why this is happening.
Edit: The reason this is happening is because this method assumes you're inheriting from ActionController::Base and not ActionController::API (which doesn't have this method). the API class is supposed to be lighter and therefore doesn't support cookies/sessions out of the box.
I'm looking for a way to configure a Rails server log only if the client has contacted a specific hostname. e.g. I could make it so that http://public.example.com doesn't get logged, but http://debug.example.com (same underlying Rails app server) does get logged (or ideally gets logged in more detail than the regular host). It would help with production debugging.
You can use gem Lograge to customize your log. This gem will give you much more custom to your log. For example, in your case, I will do this
After install the gem. Create a file at config/initializers/lograge.rb
# config/initializers/lograge.rb
Rails.application.configure do
config.lograge.enabled = true
config.lograge.custom_options = lambda do |event|
# custom log on specific domain
if event.payload[:host] == "debug.example.com"
{:host => event.payload[:host]}
else
{}
end
end
end
And in your Application Controller
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# This will add request's host to lograge so you can use it to filter log later
def append_info_to_payload(payload)
super
payload[:host] = request.host
end
end
Now you can customize your log base on domain, on how to customize it please read at: https://github.com/roidrage/lograge
Gem => https://github.com/galetahub/ckeditor
Rails = 4.1.4
I've done
rails generate ckeditor:install --orm=active_record --backend=dragonfly
ckeditor_dragonfly.rb
# Load Dragonfly for Rails if it isn't loaded already.
require "dragonfly/rails/images"
# Use a separate Dragonfly "app" for CKEditor.
app = Dragonfly[:ckeditor]
app.configure_with(:rails)
app.configure_with(:imagemagick)
# Define the ckeditor_file_accessor macro.
app.define_macro(ActiveRecord::Base, :ckeditor_file_accessor) if defined?(ActiveRecord::Base)
app.define_macro_on_include(Mongoid::Document, :ckeditor_file_accessor) if defined?(Mongoid::Document)
app.configure do |c|
# Store files in public/uploads/ckeditor. This is not
# mandatory and the files don't even have to be stored under
# public. If not storing under public then set server_root to nil.
c.datastore.root_path = Rails.root.join("public", "uploads", "ckeditor", Rails.env).to_s
c.datastore.server_root = Rails.root.join("public").to_s
# Accept asset requests on /ckeditor_assets. Again, this is not
# mandatory. Just be sure to include :job somewhere.
c.url_format = "/uploads/ckeditor/:job/:basename.:format"
end
# Insert our Dragonfly "app" into the stack.
Rails.application.middleware.insert_after Rack::Cache, Dragonfly::Middleware, :ckeditor
But when I try to do something, an error:
Dragonfly::App[:ckeditor] is deprecated - use Dragonfly.app (for the default app) or Dragonfly.app(:ckeditor) (for extra named apps) instead. See docs at http://markevans.github.io/dragonfly for details
NoMethodError: undefined method `configure_with' for Dragonfly:Module
What ideas are there to solve the problem?
UPD. If correct these errors, it becomes:
Dragonfly::Configurable::UnregisteredPlugin: plugin :rails is not registered
Remove all ckeditor initializers.
Add new file with following content:
require 'dragonfly'
# Logger
Dragonfly.logger = Rails.logger
# Add model functionality
if defined?(ActiveRecord::Base)
ActiveRecord::Base.extend Dragonfly::Model
ActiveRecord::Base.extend Dragonfly::Model::Validations
end
Dragonfly.app(:ckeditor).configure do
# this generate path like this:
# /uploads/ckeditor/AhbB1sHOgZmIjIyMDEyLzExLzIzLzE3XzIxXzAwXzY0OF9zdXJ2ZWlsbGFuY2VfbmNjbi5wbmdbCDoGcDoKdGh1bWJJI.something.png
url_format '/uploads/ckeditor/:job/:basename.:format'
# some image from previous version can break without this
verify_urls false
plugin :imagemagick
# required if you want use paths from previous version
allow_legacy_urls true
# "secure" if images needs this
secret 'ce649ceaaa953967035b113647ba56db19fd263fc2af77737bae09d452ad769d'
datastore :file,
root_path: Rails.root.join('public', 'system','uploads', 'ckeditor', Rails.env),
server_root: Rails.root.join('public')
end
Rails.application.middleware.use Dragonfly::Middleware, :ckeditor
This will store image in (old style):
{Rails.root}/public/system/uploads/ckeditor/{development,production,etc...}
Eraden, your example works. I've replaced the contents of ckeditor_dragonfly.rb with what you've given and then "rake db:migrate" was finally successfull.
But then when I upload an image I get:
NoMethodError (undefined method ckeditor_file_accessor' for #<Class:0x007fb92c720118>):
app/models/ckeditor/asset.rb:5:in'
app/models/ckeditor/asset.rb:1:in <top (required)>'
app/models/ckeditor/picture.rb:1:in'
It seems, you need to replace "ckeditor_file_accessor :data" with "dragonfly_accessor :data" in /app/model/ckeditor/asset.rb. This solved this particular error for me, though I've got another one instead, but it seems to have nothing to do with the topic discussed.
(just for the case, I will write this problem here:
DRAGONFLY: validation of property format of data failed with error Command failed ('identify' '-ping' '-format' '%m %w %h' '/var/folders/x6/pwnc5kls5d17z4j715t45jkr0000gr/T/RackMultipart20150406-2109-1ho7120') with exit status and stderr dyld: Library not loaded: /usr/local/lib/liblzma.5.dylib
Referenced from: /usr/local/bin/identify
Reason: image not found
)
In my adhearsion dialplan, I have the following code that is causing an immediate disconnect from the call without any output to the log or console:
the_flow = CallFlow.where(:dnis => dnis).first
CallFlow is a model in my rails app (gui/app/models/call_flow.rb), which lives in the gui directory of my adhearsion app. In my .ahnrc file I have:
paths:
# All paths are relative to this file's directory
init: config/startup.rb
dialplan: dialplan.rb
events: events.rb
models: gui/app/models/*.rb
And this is call_flow.rb:
class CallFlow < ActiveRecord::Base
belongs_to :routable, :polymorphic => true
def dialplan
puts self.routable.description.squeeze("\n").strip
end
def target_route=(params)
self.routable = params[:kind].constantize.new(params.reject {|k,v| k == "kind"})
end
end
And finally, I have the following line in config/startup.rb:
config.enable_rails :path => 'gui', :env => :development
I know the model works because I can create records using the rails server. But I don't even know how to get any information about what's going on to make the dialplan disconnect the call when it gets to that first line above.
Some things to check:
Ensure you have set logging to :debug in config/startup.rb
Ensure you have enabled either Rails integration or database integration, not both.
If you are running a version of Adhearsion prior to 1.1.0, some exceptions that occur in dialplan.rb may be silently lost. Consider upgrading to 1.1.0 or later (1.2.0 is current stable) and create an exception handler. This can be a simple message logger or you can report exceptions to Airbrake. See the bottom of this post for a simple Adhearsion exception logger.
Try starting the Adhearsion console to see if your models are loaded at all. Start the Adhearsion console with ahn start console /path/to/ahn/app. You will then have a console similar to the Rails console and should have access to all your ActiveRecord models (assuming the Rails integration loaded correctly).
Example exception logger for Adhearsion 1.1.0 or later. Put this in your events.rb:
events.exception.each do |e|
ahn_log.error e.message
ahn_log.debug e.backtrace.join("\n")
end
General notes on Rails vs. Database integration for Adhearsion:
For Rails integration have a line something like config.enable_rails :path => '/path/to/rails/app', :env => :production
For database integration, use something like:
config.enable_database :adapter => 'mysql',
:username => 'root',
:password => '',
:host => 'localhost'
For database integration only (not Rails integration), you should make sure that your models are in a place where Adhearsion can find them. The default location is models/ but this can be changed by editing the .ahnrc file in the Adhearsion app's base directory.
try to run this code in rails console
first start the console
bundle exec rails console
and then try to run the code which is causing the issue
CallFlow.where(:dnis => "something").first # replace "something" with something valid