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"
Related
I don't know that much about RUBY, just thought that you guys might help me with this. I'm using Storyblok as my headless CMS and JEKYLL when I'm building serve it this is the error that I got;
33: from C:/project/test/_plugins/storyblok_generator.rb:8:in `generate'
32: from C:/project/test/_plugins/storyblok_cms/generator.rb:12:in `generate!'
C:/project/test/vendor/cache/ruby/2.7.0/gems/storyblok-3.0.1/lib/storyblok/client.rb:354:in `block (2 levels) in find_and_fill_links': undefined method `[]' for nil:NilClass (NoMethodError)
the code below is from _plugins/storyblok_cms/generator.rb
def generate!
timestamp = Time.now.to_i
links = client.links(cv: timestamp)['data']['links']
stories = client.stories(per_page: 100, page: 1, cv: timestamp)['data']['stories'] #line 12
stories.each do |story|
# create all pages except global (header,footer,etc.)
content_type = story['content']['component']
if content_type != 'shared'
site.pages << create_page(site, story, links)
end
rescue UnknownContentTypeError => e
# for production, raise unknown content type error;
# for preview and other environments, issue an warning only since the content_type might be available
# but the code handling that content type might be in a different branch.
Jekyll.env == 'production' ? raise : Jekyll.logger.warn(e.message)
end
site.data['stories'] = stories
site.data['articles'] = stories.select { |story| story['full_slug'].start_with?('articles') }
site.data['shared'] = stories.select { |story| story['full_slug'].start_with?('shared') }
end
the code below is from _plugins/storyblok_generator.rb
require "storyblok"
module Jekyll
class StoryblokGenerator < Jekyll::Generator
safe true
def generate(site)
StoryblokCms::Generator.new(site).generate! #line 8
end
end
end
Additional Info:
ruby version: ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x64-mingw32]
jekyll version: jekyll 4.2.1
OS: Windows 10
I've actually found the solution to this, So this error occurs because I have created a page template in Block Library in Storyblok and then firing bundle exec jekyll serve command in terminal without creating the page template source/file in my project directory.
So I have an about_us block (content-type) in Block Library created and then when I fire bundle exec jekyll serve without creating an about_us.html first in _layouts folder, It would trigger the error.
Solution;
Make sure to create the source/file first in the _layouts folder if you have created a block (content-type) in block library.
In my Rails project, I saw the link_to is overridden in config/initializers/extend_action_view.rb
module ActionView
module Helpers
def link_to(name, options = {}, html_options = nil)
...
end
end
end
I found that with the famous command line in linux grep -r 'def link_to' *.
My question is : Is there a way to find out it in rails console ? Is there a native function rails or ruby can give us the path of file ? Something like .ancestors for a object.
ps: My IDE is vi
If you use the pry gem, you can find it by using Method#source_location.
Pass binding.pry in your view and render it. Then write:
method(:link_to).source_location
=> ["path_to_helper.rb", 124]
Use $ command in pry gem
Insert binding.pry in your code, which sets a breakpoint and then in the Pry commandline use the $ command
[1] pry(#<AdminController>)> $ Person.find
From: /Users/joe_example/.rvm/gems/ruby-1.9.3-p551/gems/composite_primary_keys-8.1.0/lib/composite_primary_keys/core.rb # line 21:
Owner: ActiveRecord::Core::ClassMethods
Visibility: public
Number of lines: 38
def find(*ids) # :nodoc:
# We don't have cache keys for this stuff yet
return super unless ids.length == 1
...
The $ command is literally worth dollars. It shows you where a method is defined as well as the source code.
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
)
I am writing a Rails 3.2 generator and would like to use Thor::Shell::Basic instance methods (e.g. ask or yes?) like they do in the official Rails guides on Application Templates.
module MyNamespace
class ScaffoldGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
if yes? "Install MyGem?"
gem 'my_gem'
end
run 'bundle install'
end
end
This will give me a NoMethodError: undefined method 'yes?' for MyNamespace::ScaffoldGenerator:Class.
I cannot figure out a clean way to make those instance methods available - I am already inheriting from Rails::Generators::Base.
Edit:
Ah, it probably has nothing to do with Thor... I get a warning:
[WARNING] Could not load generator "generators/my_namespace/scaffold/scaffold_generator"
Something is not set up correctly although I used the generator for generating generators...
Oh, yes, it does have to do something with Thor.
Do not let yourself get confused by the warning. You know that Rails::Generators uses Thor, so walk over to the Thor Wiki and check out how Thor tasks work.
The rails generator execution will call any method in your generator. So make sure that you organize your stuff into methods:
module MyNamespace
class ScaffoldGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def install_my_gem
if yes? "Install MyGem?"
gem 'my_gem'
end
end
def bundle
run 'bundle install'
end
end
end
Be sure to put your generator into the right folder structure, e.g. lib/generators/my_namespace/scaffold_generator.rb.
Thanks for asking your question, dude!
I wrote a little monkeypatch to the Rails MySQLAdapter and want to package it up to use it in my other projects. I am trying to write some tests for it but I am still new to testing and I am not sure how to test this. Can someone help get me started?
Here is the code I want to test:
unless RAILS_ENV == 'production'
module ActiveRecord
module ConnectionAdapters
class MysqlAdapter < AbstractAdapter
def select_with_explain(sql, name = nil)
explanation = execute_with_disable_logging('EXPLAIN ' + sql)
e = explanation.all_hashes.first
exp = e.collect{|k,v| " | #{k}: #{v} "}.join
log(exp, 'Explain')
select_without_explain(sql, name)
end
def execute_with_disable_logging(sql, name = nil) #:nodoc:
#Run a query without logging
#connection.query(sql)
rescue ActiveRecord::StatementInvalid => exception
if exception.message.split(":").first =~ /Packets out of order/
raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information. If you're on Windows, use the Instant Rails installer to get the updated mysql bindings."
else
raise
end
end
alias_method_chain :select, :explain
end
end
end
end
Thanks.
General testing
You could start reading about testing.
After you are understanding the basics of testing, you should think what you have changed. Then make some tests which test for
the original situation, resulting in errors since you updated it. So reverse the test after it indeed is working for the original situation.
the new situation to see whether you have implemented your idea correctly
The hardest part is to be sure that you covered all situations. Finally, if both parts pass then you could say that your code it working as expected.
Testing gems
In order to test gems you can run
rake test:plugins
to test all plugins of your rails application (see more in chapter 6 of the testing guide), this only works when the gem is in the vendor directory of an application.
Another possibility is to modify the Rakefile of the gem by including a testing task. For example this
desc 'Test my custom made gem.'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
would run all available tests in the test directory ending with _test.rb. To execute this test you can type rake test (from the gem directory!).
In order to run the tests for the gem by default (when typing just rake) you can add/modify this line:
task :default => :test
I used the second method in my ruby-bbcode gem, so you could take a look at it to see the complete example.