I am trying to write a pre-processing plugin to act on one variable in the YAML frontmatter of the pages in a collection of a Jekyll site.
I can see and print the variable, but cannot set it again, resulting in the error:
/jekyll/document.rb:407:in `method_missing': undefined method `[]=' for #<Jekyll::Document _events/2017-03-09-will.md collection=events> (NoMethodError)
Did you mean? []
Here is the actual plugin:
re = /[0-9][0-9]:[0-9][0-9]$/
Jekyll::Hooks.register :site, :pre_render do |site|
site.collections['events'].each do |event|
hour=event['hour'].to_s
if
re.match?(hour)
then
print event['hour']
end
event["hour"] = hour
end
end
Related
I am trying to play around with the RODA Ruby web framework based on Rack. However, I am having issues with using Minitest with the framework. RSpec was hectic with it too unlike Rails. I tried to reproduce the error with pry, but I couldn't make sense of it. How should I fix this? I am getting
undefined method `entry_mapping' for nil:NilClass.
Below is the associated code:
Gemfile
gem 'contentful_model', '~> 1.3' # ActiveModel-like wrapper for the Contentful SDKs
group :test do
gem 'capybara'
gem 'minitest', '>= 5.7.0'
gem 'minitest-hooks', '>= 1.1.0'
gem "minitest-global_expectations"
gem "warning"
gem 'pry'
end
models/recipe.rb
require 'contentful_model'
class Recipe < ContentfulModel::Base
self.content_type_id = 'recipe'
def self.all_recipes
all.load!
end
end
app.rb | Tree Routing
require './.env' if File.exist?(".env.rb")
require './config/initializers/contentful_model'
require 'roda'
require './models/recipe'
require 'tilt/sass'
class App < Roda
hash_routes do
view '', 'index'
end
route do |r|
#recipes = Recipe.all_recipes
r.public
r.assets
check_csrf!
r.hash_routes('')
r.get String do |id|
#recipe_details = Recipe.find(id)
next unless #recipe_details
view 'show'
end
end
end
spec/models/spec_helper.rb
ENV["RACK_ENV"] = "test"
require_relative '../../models/recipe'
require_relative '../minitest_helper'
spec/models/recipe_spec.rb
require_relative 'spec_helper'
describe Recipe do
let(:recipes) { Recipe.all_recipes }
describe '.all_recipes' do
it 'return all records with content type recipe' do
recipes = Recipe.all_recipes # undefined method `entry_mapping' for nil:NilClass
expect(recipes).to all must_be Recipe
end
end
end
pry debug
From: /Users/tiwa/RubymineProjects/marley-spoon-roda/spec/models/recipe_spec.rb:27 .all_recipes#test_0001_return all records with content type recipe:
24: it 'return all records with content type recipe' do
25: recipes = Recipe.all_recipes # undefined method `entry_mapping' for nil:NilClass
26: binding.pry
=> 27: expect(recipes).to all must_be Recipe
28: end
[1] pry(#<.all_recipes>)> Recipe.all_recipes
NoMethodError: undefined method `entry_mapping' for nil:NilClass
from /Users/tiwa/.gem/ruby/2.7.1/gems/contentful_model-1.3.0/lib/contentful_model/base.rb:124:in `mapping?'
I see the code in contentful_model-1.3.0/lib/contentful_model/base.rb:124 is:
ContentfulModel.configuration.entry_mapping.key?(#content_type_id)
If error msg is undefined method `entry_mapping' for nil:NilClass then
ContentfulModel.configuration
Is nil
To fix this you need configure ContentfulModel. Something like that:
ContentfulModel.configure do |config|
config.access_token = "your access token in here" # Required
config.preview_access_token = "your preview token in here" # Optional - required if you want to use the preview API
config.management_token = "your management token in here" # Optional - required if you want to update or create content
config.space = "your space id in here" # Required
config.environment = "master" # Optional - defaults to 'master'
config.default_locale = "en-US" # Optional - defaults to 'en-US'
config.options = { # Optional
# Extra options to send to the Contentful::Client and Contentful::Management::Client
# See https://github.com/contentful/contentful.rb#configuration
# Optional:
# Use `delivery_api` and `management_api` keys to limit to what API the settings
# will apply. Useful because Delivery API is usually visitor facing, while Management
# is used in background tasks that can run much longer. For example:
delivery_api: {
timeout_read: 6
},
management_api: {
timeout_read: 100
}
}
end
With this config this call is not more nil
ContentfulModel.configuration
See https://github.com/contentful/contentful_model
I'm currently trying to run a Rake task in a Ruby project (No Rails). What I am trying to accomplish is to run a method from a file within my Ruby project. However I get the following error:
undefined method `namespace' for main:Object (NoMethodError)
I created a folder task that holds a test.rb file. Before I had it as test.rake but I think this was incorrect. I also created a Rakefile pointing to task/test.rb
For redeability, I'm using namespace: although I'll be honest I'm not sure if I even need it.
#Rakefile
task :default => [:test]
task :test do
ruby 'task/test.rb'
end
Here is the task.test.rb
require './src/lambda_function.rb'
class KMS
def initialize
end
def decrypt(key)
return "some password"
end
end
class SNS
def initialize
end
end
TEST_FORM_ID=123
namespace :test do
namespace :lambda do
desc 'Run the Lambda process function'
task :process do
LambdaFunctions::LambdaHandler.process(box_api: BoxApi.new,
form: TEST_FORM_ID,
sns: SNS.new,
kms: KMS.new)
end
end
end
What I'm I doing wrong?
So, I'm new to Ruby and I'm trying to install this photo gallery to my Jekyll blog. However, when I'm trying to run
jekyll build
I get this error message:
Liquid Exception: undefined method `[]' for nil:NilClass in photography/index.html
jekyll 3.7.2 | Error: undefined method `[]' for nil:NilClass
With --trace it points me to:
/Users/hal9000/Desktop/Plommonstop/_plugins/jekyll-exiftag-mod.rb:18:in `render': undefined method `[]' for nil:NilClass (NoMethodError)
But now I don't understand how to proceed. jekyll-exiftag-mod looks like this:
require 'exifr/jpeg'
#Based on https://github.com/benib/jekyll-exiftag by Beni Buess (MIT License)
#Edited to work as a Liquid-Block instead of a Liquid-Tag, reads the filename from between the
#brackets. --T.Winter
module Jekyll
class ExifTag < Liquid::Block
def initialize(tag_name, params, token)
super
#args = self.split_params(params)
end
def render(context)
#abort context.registers[:site].config['source'].inspect
sources = Array.new(context.registers[:site].config['exiftag']['sources'])
# first param is the exif tag
tag = #args[0]
# if a second parameter is passed, use it as a possible img source
if #args.count > 1
sources.unshift(#args[1])
end
# the image can be passed as the third parameter
img = super
# first check if the given img is already the path
if File.exist?(img)
file_name = img
else
# then start testing with the sources from _config.yml
begin
source = sources.shift
file_name = File.join(context.registers[:site].config['source'], source, img)
end until File.exist?(file_name) or sources.count == 0
end
# try it and return empty string on failure
begin
exif = EXIFR::JPEG::new(file_name)
return tag.split('.').inject(exif){|o,m| o.send(m)}
rescue
"ERROR, EXIF-Tag RB"
end
end
def split_params(params)
params.split(",").map(&:strip)
end
end
end
Liquid::Template.register_tag('exiftag', Jekyll::ExifTag)
With row 18:
sources = Array.new(context.registers[:site].config['exiftag']['sources'])
What does it mean with "Undefined method `[]' for nil:NilClass?" And what exactly is making this problem occur?
The error could simply mean that you have not set ['exiftag']['sources'] in your config file.
Your config file should have something similar to below (entry1 and entry2 are just examples):
exiftag:
sources:
- entry1
- entry2
Do note, indentation is important in YAML as well..
Trying to build a gem to use it for Logstash as a filter. I'm using classes and methods from a .jar file.
The following is my Jruby code so far:
# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require 'java'
require 'Processing.jar'
java_import 'process.Process'
class LogStash::Filters::Process < LogStash::Filters::Base
config_name "process"
StringPath = "/path/to/file/"
ML = JavaUtilities.get_proxy_class('processing.Processing')
#ML = ML.new(StringPath)
public
def register
end
public
def filter(event)
event["result"] = #ML.Process("any string.")
filter_matched(event)
end
end
However, it gave me the following error:
←[31mException in filterworker, the pipeline stopped processing new events, plea
se check your filter configuration and restart Logstash. {"exception"=>#<NoMetho
dError: undefined method 'Process' for nil:NilClass>, "backtrace"=>[
"/path/to/logstash-2.0.0/vendor/local_gems
/dda91dc0/logstash-filter-Process-0.5.0/lib/logstash/filters/processing.rb:54:in 'filter'", "/path/to/log
stash-2.0.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.0.0-java/lib/logstash/f
ilters/base.rb:152:in 'multi_filter'", "org/jruby/RubyArray.java:1613:in 'each'"
, "/path/to/logstash-2.0.0/vendor/bundle/j
ruby/1.9/gems/logstash-core-2.0.0-java/lib/logstash/filters/base.rb:149:in 'mult
i_filter'", "(eval):233:in 'filter_func'", "/path/to/logstash-2.0.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.0.0-java/
lib/logstash/pipeline.rb:219:in 'filterworker'", "path/to/log/logstash-2.0.0/vendor/bundle/jruby/1.9/gems/logstash-core-2.0.0
-java/lib/logstash/pipeline.rb:154:in 'start_filters'"], :level=>:error}←[0m
NoMethodError: undefined method 'Process' for nil:NilClass
filter at /path/to/logstash-2.0.0
/vendor/local_gems/dda91dc0/logstash-filter-Process-0.5.0/lib/logstash
/filters/Process.rb:54
multi_filter at /path/to/logstash-2.0.0
/vendor/bundle/jruby/1.9/gems/logstash-core-2.0.0-java/lib/logstash/filters/base
.rb:152
each at org/jruby/RubyArray.java:1613
multi_filter at /path/to/logstash-2.0.0
/vendor/bundle/jruby/1.9/gems/logstash-core-2.0.0-java/lib/logstash/filters/base
.rb:149
filter_func at (eval):233
filterworker at /path/to/logstash-2.0.0
/vendor/bundle/jruby/1.9/gems/logstash-core-2.0.0-java/lib/logstash/pipeline.rb:
219
start_filters at /path/to/logstash-2.0.0
/vendor/bundle/jruby/1.9/gems/logstash-core-2.0.0-java/lib/logstash/pipeline.rb:
154
I tried the following:
.
.
.
public
def filter(event)
StringPath = "/path/to/file/"
ML = JavaUtilities.get_proxy_class('processing.Processing')
#ML = ML.new(StringPath)
event["result"] = #ML.Process("any string.")
filter_matched(event)
end
end
But it gave me the error:
SyntaxError: dynamic constant assignment error.
I tried this in a normal jruby file and everything worked with me. Using Logstash's filter however is what seems to be giving me an issue here.
It seems you are struggling with local and instance variables in Ruby. Please see this blog post for more information.
When you call event["result"] = ML.Process(event["text"]) ruby tries to find a local variable named ML which doesn't exist. Therefore you get undefined local variable or method ML.Process(event["text"]). So, messing around with your variables might solve your problem.
#ML is an instance variable and is available in all methods calling it using #ML or self.ML. Please try this:
public
def filter(event)
event["result"] = #ML.Process(event["text"])
filter_matched(event)
end
Things I stumbled upon:
Where do MLVectorPath and MLStopWordPath come from?
What is StringPath? It is assigned but never used.
Do you have a field text? Otherwise change event["text"] into event["message"].
However, I know neither your Java code nor your logstash configuration so these things may be okay. Please let me know if this helps.
I have a module in app/misc/dsl/builder.rb that has this code
module Dsl
class Builder
def initialize(context, &block)
return if not block_given?
parent_context = block.binding.eval "self"
parent_context.extend Proxy
parent_context.object = context
parent_context.instance_eval &block
end
end
def self.set_context(context, &block)
Dsl::Builder.new(context, &block)
end
end
Note: this directory misc is preloaded in application.rb
config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**/}'),
Rails.root.join('app', 'misc', '{**/}')
]
Then, somewhere in the text (lets say at foo.rb) I have this code:
Dsl.set_context(obj) do
#some code with obj receiving messages
end
The test stack we are using consists on Zeus+Guard+Rspec. Now, lets say I rewrite the code to something not working
Dsl.set_context(obj) do
asdqwe #this message does not exists
end
From times to times, I receive this baffling message
1) SomeOtherClass search_hash receiving keywords params should query for those keywords
Failure/Error: subject.search_hash
NoMethodError:
undefined method `set_context' for Dsl:Module
# ./app/misc/product_query.rb:116:in `base_search_hash'
# ./app/misc/product_query.rb:25:in `search_hash'
# ./spec/misc/product_query_spec.rb:78:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
instead of the correct message that should be regarding undefined method asdqwe
Any clue about this?
Look here
it says:
Rails 3 has been updated such that classes/modules (henceforth, C/M)
are lazy loaded from the autoload paths as they are needed
so, you can do require_relative 'app/misc/dsl/builder.rb' in your rspec_helper.rb (can it be better with just require?) The problem must be that the loader doesn't know in advance where to find Dsl.set_context, but he will know once you have referenced Dsl::Builder
Hope it helps