Ruby - Error: undefined method `[]' for nil:NilClass - ruby

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..

Related

Jekyll Hooks plugin not able to change frontmatter values

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

undefined method `+' for nil:NilClass (NoMethodError) ruby

trying to build a pptx to scorm converter. I get an error NoMethodError Undefined method `+' for NilClass. I guess it may be due to a defined method. any idea on how i can remove this error ?
dir = ARGV.shift
dest = ARGV.shift
pptx = dir + "/presentation.pptx"
lis = []`enter code here`
STDERR.puts "Copy template => #{dest}"
FileUtils.cp_r "template", dest
Dir["#{dir}/*.PNG"].each do |file|
STDERR.puts "Copy #{file} => #{dest}/img"
FileUtils.cp file, "#{dest}/img/"
STDERR.puts "Creating thumb #{file} => #{dest}/img/thumb"
name = file.split(/\//).last
system "/usr/bin/convert", "-scale", "200x", file, "#{dest}/img/thumb/#{name}"
lis.push name
end
ordered = lis.sort_by { |x| x[/\d+/].to_i }
DIR is nil
If you debug your code as follows:
puts dir.nil? # true
So, in order to run this code you must provide the ruby shell with 2 arguments, as follows:
ruby test.rb DIRECTORY_NAME DESTINATION_NAME

NoMethodError but did 'require_relative'

I did the 'requir_relative' but still got the NoMethodError.
There are 2 ruby files, under 'run.rb' I have this
class Run
def separate(data)
hash_block = []
(0...data.count).each do |i|
f = data[i].split('|')
hash_block[i] = Hashing.new(f[0].to_i, f[1], f[2], f[3], f[4])
end
hash_block
end
end
and then in the main file, I did these:
require_relative 'run'
...some codes...
to_separate = IO.readlines(ARGV[0])
separated = separate(to_separate)
...some codes...
but I still get this:
in `block in <main>': undefined method `separate' for main:Object (NoMethodError)
If I cut the method and paste it in the main file it will work as expected but that is something I wanted to avoid.
In order to call the method within the class Run you have to instantiate it. Since is an instance method. The way your calling the class is giving you the error undefined because it can not find it with in the scope of your current file
run_instance = Run.new
to_separate = IO.readlines(ARGV[0])
sperated = run_instance.separate(to_separate)
You required the file, but in that file you have a class definition. separate is inside that class (and that's an instance method), so you need an object to call the method on.
separated = Run.new.separate(to_separate)

Chef recipe gives error as undefined method 'split'

I am using this code in my Chef recipe. It works fine with all the other existing servers, however it doesn't work well with my new server:
user_array = node
node['user']['user_array_node_attr'].split("/").each do |hash_key|
user_array = user_array.send(:[], hash_key)
end
It returns an error:
FATAL: NoMethodError: undefined method 'split' for nil:NilClass
You don't have any value in
node['user']['user_array_node_attr'] #=> nil
You can check for the presence
node['user']['user_array_node_attr'].present? && node['user']['user_array_node_attr'].split("/").each do |hash_key|
user_array = user_array.send(:[], hash_key)
end

Rails 4: Undefined method on module

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

Resources