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
)
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 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
I have a problem with my rails application. After an Update from Rails 3 to 4.
When I surf through the pages after starting the server in development mode everything is fine.
But after a single code change (even adding a space) every page request shows the following error.
Unable to autoload constant User, expected
/path/to/my/rails-app/app/models/user.rb to define it
The file lives exactly there and defines the class:
class User < ActiveRecord::Base
…
I tried many things with config.autoload_paths and config.eager_load_paths in application.rb but with no luck.
Deactivating spring did not help either.
Developing an app and having to restart the server after every single change seems so 90s.
$ rails -v
Rails 4.2.4
$ ruby -v
ruby 2.1.7p400 (2015-08-18 revision 51632) [x86_64-linux]
Some relevant configs:
development.rb
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {
host: 'localhost',
port: 3000
}
end
application.rb
module Serviceportal
class Application < Rails::Application
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
[… some asset precompile stuff …]
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = 'utf-8'
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += Dir["#{config.root}/app/mailers",
"#{config.root}/app/controllers/concerns",
"#{config.root}/app/models/concerns",
"#{config.root}/app/decorators/concerns",
"#{config.root}/lib",
"#{config.root}/lib/shared"
]
config.eager_load_paths += Dir["#{config.root}/app/mailers",
"#{config.root}/app/controllers/concerns",
"#{config.root}/app/models/concerns",
"#{config.root}/app/decorators/concerns",
"#{config.root}/lib",
"#{config.root}/lib/shared"]
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Berlin'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :de
[… some SQL and active support stuff …]
config.action_controller.include_all_helpers = false
config.action_controller.action_on_unpermitted_parameters = :raise
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
Edit: The error mostly shows up in lib/auth/user_proxy.rb in the following function. Maybe this helps to narrow the range of possible causes.
def self.usertype_allowed?(type)
[ User, TempCustomer ].include? type.classify.safe_constantize rescue false
end
Edit 2: Stringify the class names in Edit 1 helped (thanks #Benjamin Sinclaire). But only leads to the next errors. I could also avoid using classes. But at the following error in app/controllers/concerns/security.rb there is nothing can change?
Unable to autoload constant User, expected
/path/to/my/rails-app/app/models/user.rb to define it
code:
def set_current_user
User.current = current_user
end
with current user saved in the Thread (code from /path/to/my/rails-app/app/models/user.rb
def self.current
Thread.current['current_user']
end
def self.current=(user)
Thread.current['current_user'] = user
end
Just to make it clear again: It works after server restart in development until I change some code somewhere.
1 See if you have any multiple-level class or module declaration done one one line and change them to be declared in several lines.
Instead of
class Parent::Sub::Child
end
Do
module Parent
module Sub
class Child
end
end
end
2 Check your model association definitions, and ensure you are never using constant. Use string instead.
Instead of
belongs_to :manager, class_name: User
Do
belongs_to :manager, class_name: 'User'
3 Just saw your edit. Can you refactor like this?
# I assume `type` is a string or such, so we can compare classes
# names instead of constants, and get rid of `safe_constantize`
def self.usertype_allowed?(type)
['User', 'TempCustomer'].include? type.classify rescue false
end
4 Not a good idea to serialize an active record object in the Thread storage. Change it to store the user id instead, like this:
def set_current_user
User.current = current_user.id
end
def self.current
Thread.current['current_user_id']
end
def self.current=(user_id)
Thread.current['current_user_id'] = user_id
end
You don't need include app/models/concerns and app/controllers/concerns in your autoload/ eagerload paths as they are included by default in Rails 4: https://signalvnoise.com/posts/3372-put-chubby-models-on-a-diet-with-concerns
Also make sure that your concerns are defined as modules, extend ActiveSupport::Concern and with the appropriate file name
#taggable.rb
module Taggable
extend ActiveSupport::Concern
end
Another cause of your problem might be that some modules/ classes in app/decorators/concerns, lib, lib/shared are using the User class
which is not loaded yet or some of it's dependencies are not loaded so try adding require_relative path_to_user.rb at the top of those files
-----Edit-------
Try adding at the top of lib/auth/user_proxy.rb
require_dependency 'app/models/user'
This way you'll remove any ambiguity in autoloading the User class and you won't mess around with Rails autoloading see more here: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#require-dependency , http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#common-gotchas
Same problem but in an engine w/ namespaces. No issues in production or in development until a code-change / autoload.
The solution was to
checking for double definitions (there were none)
checking if the module nesting strictly follows rails conventions in the filesystem.
I've had myns under myengine/app/myns/subns/obj.rb but myns is being ignored as it is at the root of the app folder, so moving the myns folder into a subfolder myengine/app/lib/myns solved the issue.
Note: the rails error message was very explicit about the module nesting (while still pointing to the wrong .rb file in the filesystem) so look closely at the error. The error was 'Unable to autoload constant subns/obj.rb in .../myns/subns/obj.rb'. Rails suggesting the incorrect file-location (which exists) is misleading in this case.
During a Rails/Ruby Update I found time to look into this and finally found the cause.
The user class had an unloadable in it for years. That caused the problems since Rails 4. Now I removed this and found no issues after that.
Trying to go through the tekpub rack tutorial but run into this error.
Boot Error
Something went wrong while loading app.ru
LoadError: cannot load such file -- haiku
There is a file named haiku.rb in the same directory as the app I am trying to run but I get the above error while trying to run the program. Here is the code:
class EnvironmentOutput
def initialize(app=nil)
#app = app
end
def call(env)
out = ""
unless(#app.nil?)
response = #app.call(env)[2]
out+=response
end
env.keys.each {|key| out+="<li>#{key}=#{env[key]}</li>"}
["200",{"Content-Type" => "text/html"},[out]]
end
end
require 'haml'
require 'haiku'
class MyApp
def call(env)
poem = Haiku.new.random
template = File.open("views/index.haml").read
engine = Haml::Engine.new(template)
out = engine.render(Object.new, :poem => poem)
["200",{"Content-Type" => "text/html"}, out]
end
end
use EnvironmentOutput
run MyApp.new
I'm sure its a small error as the code is the same as in the tutorial and it works for him...
Thanks
You'll want to read up on ruby load path (either $LOAD_PATH or $:). By default, ruby has a load path which includes wherever your gems are installed, which is why you can do require 'haml' without providing the full path to where your haml gem is located.
When you type require 'haiku', you're basically telling ruby to look for some file called haiku.rb somewhere in it's load path, and the LoadError comes from ruby not finding your haiku.rb file in any of the directories listed in $LOAD_PATH (or $:, which is just shorthand for $LOAD_PATH).
You can solve this in one of (at least) two ways:
change require 'haiku' to require File.dirname(__FILE__) + '/haiku.rb' to explicitly tell ruby what file to load
add the current working directory to your load path: $:.push(File.dirname(__FILE__)). This way you can keep the require 'haiku' part.
i have looked through the list of related questions however my problem does not seem to be listed and hence here it is:
Basically I'm trying to use Geokit within the Ruby on Rails environment, im not sure if i installed it properly, I have included it within the environment.rb (and done rake db:install) and i'm now trying to do the following:
require 'active_record'
require 'geokit'
class Store < ActiveRecord::Base
acts_as_mappable
end
Unforunately, when i try to run this and see if its ok, i get the following error:
c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/base.rb:1959:in `method_missing': undefined local variable or method `acts_as_mappable' for #<Class:0x4cd261c> (NameError)
from C:/Users/Erika/Documents/Visual Studio 2008/Projects/StoreLocator/StoreLocator/app/models/store.rb:5
I am running Ruby in Steel for Visual Studio 2008, i'm not sure what i'm doing wrong as all the online tutorials i find tend to be rather old and done apply to me. Any help would be greatly appreciated. thanks!
Edit: (adding as per Ben's Request)
The following is what my environment.rb looks like
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
config.gem "geokit"
config.gem "ym4r"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
# These defaults are used in GeoKit::Mappable.distance_to and in acts_as_mappable
GeoKit::default_units = :kms
GeoKit::default_formula = :sphere
# This is the timeout value in seconds to be used for calls to the geocoder web
# services. For no timeout at all, comment out the setting. The timeout unit
# is in seconds.
#GeoKit::Geocoders::timeout = 3
# These settings are used if web service calls must be routed through a proxy.
# These setting can be nil if not needed, otherwise, addr and port must be
# filled in at a minimum. If the proxy requires authentication, the username
# and password can be provided as well.
GeoKit::Geocoders::proxy_addr = nil
GeoKit::Geocoders::proxy_port = nil
GeoKit::Geocoders::proxy_user = nil
GeoKit::Geocoders::proxy_pass = nil
# This is your yahoo application key for the Yahoo Geocoder.
GeoKit::Geocoders::yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
# This is your Google Maps geocoder key.
GeoKit::Geocoders::google = 'apikey'
# This is your username and password for geocoder.us.
# To use the free service, the value can be set to nil or false. For
# usage tied to an account, the value should be set to username:password.
GeoKit::Geocoders::geocoder_us = false
# This is your authorization key for geocoder.ca.
# To use the free service, the value can be set to nil or false. For
# usage tied to an account, set the value to the key obtained from
# Geocoder.ca.
GeoKit::Geocoders::geocoder_ca = false
# This is the order in which the geocoders are called in a failover scenario
# If you only want to use a single geocoder, put a single symbol in the array.
# Valid symbols are :google, :yahoo, :us, and :ca.
# Be aware that there are Terms of Use restrictions on how you can use the
# various geocoders. Make sure you read up on relevant Terms of Use for each
# geocoder you are going to use.
GeoKit::Geocoders::provider_order = [:google]
acts_as_mappable is part of geokit-rails. You need to install the geokit-rails plugin.
script/plugin install git://github.com/andre/geokit-rails.git
To check if the plugin is properly installed, look under the vendor/plugins directory of your Rails app. It should have a geokit-rails sub directory. It it, you'll find all the plugin files, other subdirectories, including the file acts_as_mappable.rb (in vendor\plugins\geokit-rails\lib\geokit-rails).
If everything seems to be properly installed, try adding "require geokit" to the top of the init.rb file in the plugin root folder (vendor\plugins\geokit-rails).
Be sure to restart your app server after making the modifications.
What method are you using to include the geokit library? The plugin? The gem? Is the gem unpacked into vendor? What does your environment.rb look like?
Edit: I meant to leave this as a comment on the question - pardon me.