api-pagination gem configuration error in Rails 5 when deployed to heroku - heroku

I am using the api-pagination gem and deploying to heroku in a rails 5 app. My configuration is ok in development but fails in production. Here is the config file:
config/initializers/api_pagination.rb
ApiPagination.configure do |config|
# If you have both gems included, you can choose a paginator.
config.paginator = :will_paginate
# By default, this is set to 'Total'
config.total_header = 'X-Total'
# By default, this is set to 'Per-Page'
#config.per_page_header = 'X-Per-Page'
# Optional: set this to add a header with the current page number.
#config.page_header = 'X-Page'
# Optional: what parameter should be used to set the page option
config.page_param = :page
# or
config.page_param do |params|
params[:page][:number]
end
# Optional: what parameter should be used to set the per page option
config.per_page_param = :per_page
# or
config.per_page_param do |params|
params[:page][:size]
end
end
Here is the error from the heroku logs:
[INFO ] Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)
[FATAL] NoMethodError (undefined method `[]' for nil:NilClass):
[FATAL] config/initializers/api_pagination.rb:18:in `block (2 levels) in <top (required)>'
The controller action is very simple right now:
def index
listings = Listing.where(active: true)
paginate json: listings
end
I am including no parameters in the route.

In my situation, most of the configuration was unnecessary. I'm not sure why it was causing an error but the defaults for my case are fine, except that I use will_paginate. This is my config file and it works:
ApiPagination.configure do |config|
# If you have both gems included, you can choose a paginator.
config.paginator = :will_paginate
end
If someone follows up with a solution that addresses the error, I will accept it. It might be useful for someone else that requires more of the non-default settings.

Related

undefined method `entry_mapping' for nil:NilClass

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

Should I be using EM::Synchrony::Multi or EM::Synchrony::FiberIterator with Goliath?

Maybe this is the wrong approach, but I'm trying to parallelize em-hiredis puts and lookups in Goliath with EM::Synchrony::Multi or EM::Synchrony::FiberIterator. However, I can't seem to access basic values initialized in the config. I keep getting method_missing errors.
Here's the basic watered down version of what I'm trying to do:
/lib/config/try.rb
config['redisUri'] = 'redis://localhost:6379/0'
config['redis_db'] ||= EM::Hiredis.connect
config['user_agent'] = "MyCrawler Mozilla/5.0 Compat etc."
Here's the basic Goliath Setup
/try.rb
require "goliath"
require "em-hiredis"
require "em-synchrony/fiber_iterator"
require "em-synchrony/em-hiredis"
require "em-synchrony/em-multi"
class Try < Goliath::API
use Goliath::Rack::Params
use Goliath::Rack::DefaultMimeType
def response(env)
case env['REQUEST_PATH']
when "/start" then
start_crawl()
body = "STARTING"
[200, {}, body]
end
end
def start_crawl
urls = ["http://www.example.com/",
"http://www.example.com/photos/",
"http://www.example.com/video/",
]
EM::Synchrony::FiberIterator.new(urls, 3).each do |url|
p "#{user_agent}"
redis_db.sadd 'test_queue', url
end
# multi = EM::Synchrony::Multi.new
# urls.each_with_index do |url, index|
# p "#{user_agent}"
# multi.add index, redis_db.sadd('test_queue', url)
# end
end
end
However, I keep getting errors where Goliath doesn't know what user_agent is or redis_db which were initialized in the config.
[936:INFO] 2012-09-21 23:47:10 :: Starting server on 0.0.0.0:9000 in development mode. Watch out for stones.
/Users/ewu/.rvm/gems/ruby-1.9.3-p194#crawler/gems/goliath-1.0.0/lib/goliath/api.rb:143:in `method_missing': undefined local variable or method `user_agent' for #<Try:0x007ff5a431c4e0 #opts={}> (NameError)
from ./lib/try.rb:27:in `block in start_crawl'
from /Users/ewu/.rvm/gems/ruby-1.9.3-p194#crawler/gems/em-synchrony-1.0.2/lib/em-synchrony/fiber_iterator.rb:10:in `call'
from /Users/ewu/.rvm/gems/ruby-1.9.3-p194#crawler/gems/em-synchrony-1.0.2/lib/em-synchrony/fiber_iterator.rb:10:in `block (2 levels) in each'
...
...
...
Ideally I'd be able to get FiberIterator working, because I have additional conditionals to check for:
EM::Synchrony::FiberIterator.new(urls, 3).each do |new_url}
is_member = redis_db.sismember('crawled_urls', new_url)
is_member += redis_db.sismember('queued_urls', new_url)
if is_member == 0
redis_db.lpush 'crawl_queue', new_url
redis_db.sadd 'queued_urls', new_url
end
end
I don't think your config file is getting loaded. The name of try.rb needs to match the name of the robojin.rb file in the config directory.

Sinatra, Mongoid, Heroku, MongoHQ: connecting to Mongodb

Trying to get Mongoid up and running with Sinatra on Heroku (MongoHQ). Previous experience with Rails but first time with the stack and Sinatra.
Started with one of the simple examples on the web (app.rb):
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongoid'
configure do
Mongoid.load!('mongoid.yml')
Mongoid.configure do |config|
if ENV['MONGOHQ_URL']
conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
uri = URI.parse(ENV['MONGOHQ_URL'])
# problem happens here
config.master = conn.db(uri.path.gsub(/^\//, ''))
else
config.master = Mongo::Connection.from_uri("mongodb://localhost:27017").db('test')
end
end
end
# Models
class Counter
include Mongoid::Document
field :count, :type => Integer
def self.increment
c = first || new({:count => 0})
c.inc(:count, 1)
c.save
c.count
end
end
# Controllers
get '/' do
"Hello visitor n" + Counter.increment.to_s
end
For reference, mongoid.yml looks like:
development:
sessions:
default:
database: localhost
production:
sessions:
default:
uri: <%= ENV['MONGOHQ_URL'] %>
As per app.rb (# problem happens here), my logs say:
/app/app.rb:15:in `block (2 levels) in <top (required)>': undefined method `master=' for Mongoid::Config:Module (NoMethodError)
from /app/vendor/bundle/ruby/1.9.1/gems/mongoid-3.0.3/lib/mongoid.rb:112:in `configure'
from /app/app.rb:11:in `block in <top (required)>'
from /app/vendor/bundle/ruby/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:1273:in `configure'
from /app/app.rb:8:in `<top (required)>'
I have also tried variants, including:
config.master = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXX')
Mongoid.database = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXXXX')
But get the same error:
undefined method `master` for Mongoid::Config:Module (NoMethodError)
or:
undefined method `database=` for Mongoid::Config:Module (NoMethodError)
What am I missing?
Shouldn't be
configure do
Mongoid.load!('mongoid.yml')
end
enough?
That's what the mongid docs are saying. The MONGOHQ_URL environment variable already contains every information to initialize the connection to the db.
So was using Mongoid 3.x ... which:
Doesn't use 10gen driver: uses Moped
Doesn't use config.master
The canonical sample code above which is all over the web works out of the box with Mongoid 2.x so have dropped back to that for the time being.
Thanks!

I can't get a backtrace in Rails 3

I'm trying to run the usual rails commands (rails s, rails g, rails c, etc) and I'm getting errors (because I'm migrating from MRI ruby and postgres to jruby and neo4j), which would be fine if only there was a stack trace.
It looks like this:
$ rails s
NameError: uninitialized constant Authorization::ActiveRecord
I'm expecting errors like this because Neo4j doesn't use ActiveRecord and it no longer exists, but I really need to see which file is calling ActiveRecord so I can fix this. But nothing I've found from google or tried in the code has brought the backtrace back to me. ;_;
My config/application.rb is:
require File.expand_path('../boot', __FILE__)
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'active_resource/railtie'
require 'rails/test_unit/railtie'
require 'sprockets/railtie'
require 'neo4j'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in pro duction, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module MyApp
class Application < Rails::Application
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, chanmge this if you want to expire all your assets
config.assets.version = '1.1'
# 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.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# this was done to load all modules in lib
# following directions at: https://stackoverflow.com/questions/3356742/best-way-to-load-module-class-from-lib-folder-in-rails-3/3962321#3962321
config.autoload_paths += Dir["#{config.root}/lib/**/"]
#for rails-ckeditor
config.autoload_paths += %W( #{config.root}/app/models/ckeditor )
# 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 ]
# 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. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end
And my config/environments/development.rb is:
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
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
#config.action_view.debug_rjs = true $ turn off for rails 3.1
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
#Devise wants this:
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# 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
config.log_level = :debug
# Do not compress assets
config.assets.compress = false
# Expand the lines which load the assets
config.assets.debug = true
end
I'm not aware of any other files that might effect the logger/backtrace situation. I'd include more but this feels like such a general problem I'm really not sure what to include.
Update: I'm pretty sure this question is a duplicate of here (althought I'm trying to get it working in any environment).

Thin throws error: undefined method "call"

I'm having trouble getting thin to run my webapp. It starts up just fine, but whenever I make a request thin craps out and I get the following popping up in the log:
>> Listening on 0.0.0.0:3000, CTRL+C to stop
!! Unexpected error while processing request: undefined method `call'
for #<Rack::Request:0x7f104facb640>
This configuration worked just fine on my Debian server; I'm running Gentoo now.
This is my rackup file:
require 'toto'
# Rack config
use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico', '/pubkey.asc'], :root => 'public'
use Rack::Request
use Rack::CommonLogger
if ENV['RACK_ENV'] == 'development'
use Rack::ShowExceptions
end
#
# Create and configure a toto instance
#
toto = Toto::Server.new do
#
# Add your settings here
# set [:setting], [value]
#
set :author, "jibcage" # blog author
set :title, "Going to Grass" # site title
set :root, "index" # page to load on /
# set :date, lambda {|now| now.strftime("%d/%m/%Y") } # date format for articles
set :markdown, :smart
Delete the line
use Rack::Request

Resources