Sinatra CarrierWave Fog - NameError: uninitialized constant Fog - ruby

I have been trying to setup CarrierWave with Sinatra and Fog for S3 File Management. I constantly keep running into issues around Fog being undefined. This works fine the moment I change the storage to :file.
I have so far also tried solutions mentiohed here NameError: uninitialized constant CarrierWave::Storage::Fog and here NameError: uninitialized constant CarrierWave::Storage::Fog, heroku
But I have had no luck so far.
Here's my overall setup
Gemfile
gem 'fog', require: 'fog/aws'
gem 'carrierwave', '~> 2.0'
app.rb
require "carrierwave"
CarrierWave.configure do |config|
config.fog_credentials = {
provider: 'fog/aws', # required
aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'], # required unless using use_iam_profile
aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], # required unless using use_iam_profile
use_iam_profile: true, # optional, defaults to false
region: ENV['AWS_REGION'], # optional, defaults to 'us-east-1'
}
config.fog_directory = ENV['S3_BUCKET_NAME']
config.fog_public = false # optional, defaults to true
config.fog_attributes = { cache_control: "public, max-age=#{365.days.to_i}" } # optional, defaults to {}
config.fog_provider = 'fog/aws'
end
Added this to my user class
mount_uploader :profile_picture, ProfileImageUploader
And lastly my ProfileImageUploader
class ProfileImageUploader < CarrierWave::Uploader::Base
storage :fog
end
I am still stuck at this output
NameError: uninitialized constant Fog
from ~/.rvm/gems/ruby-2.7.0/gems/carrierwave-2.1.0/lib/carrierwave/storage/fog.rb:159:in `connection'

try using
gem 'fog-aws'
and then
require 'sinatra/activerecord'
require 'carrierwave'
require 'carrierwave/orm/activerecord'
require 'fog/aws'

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

undefined method `min_cost' for ActiveModel::SecurePassword:Module

I am following Michale harlt's ruby on rails tutorial.Everything was going fine uptill I got stuck into this problem in which after giving user name and password and clicking on "Login" push button and I am getting an error "undefined method `min_cost' for ActiveModel::SecurePassword:Module".I am trying to resolve this issue from last 2 days but could'nt able to find any relevant solution.
Please help me to solve this.Thanks in advance.Here are all my relevant files of project. (I am using rails 3.2.16)
For any further information please let me know.
user.rb
class User < ActiveRecord::Base
attr_accessor :remember_token
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
end
sessions_helper.rb
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Remembers a user in a persistent session.
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
#current_user ||= User.find_by_id(user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by_id(user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
#current_user = user
end
end
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Log Out Current User
def log_out
session.delete(:user_id)
#current_user = nil
end
end
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
remember user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out
redirect_to home_path
end
end
GemFile
source 'https://rubygems.org'
gem 'rails', '3.2.16'
gem 'bcrypt-ruby', '~> 3.1.2'
gem 'strong_parameters'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
group :development, :test do
gem 'sqlite3', '1.3.9'
gem 'guard'
end
group :test do
gem 'minitest-reporters'
gem 'mini_backtrace', '0.1.3'
gem 'guard-minitest', '2.3.1'
end
group :production do
gem 'pg', '0.17.1'
gem 'rails_12factor', '0.0.2'
gem 'puma', '2.11.1'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'coffee-rails', '~> 3.2.1'
gem 'sass-rails', '>= 3.2'
gem 'bootstrap-sass', '~> 3.3.4'
gem 'sprockets-rails', '=2.0.0.backport1'
gem 'sprockets', github: 'tessi/sprockets', branch: '2_2_2_backport2'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
Application Trace
app/models/user.rb:14:in `digest'
app/models/user.rb:27:in `remember'
app/helpers/sessions_helper.rb:10:in `remember'
app/controllers/sessions_controller.rb:10:in `create'
As far as I remember, SecurePassword#min_cost appeared in rails4 (or in rails3 > 3.2.16.)
Since you are just learning, my advice would be not to concentrate on solving this particular error, but just substitute the problematic line with:
cost = BCrypt::Engine::MIN_COST
or even with
cost = 10
and go further. Whether you are still to fix this, you should upgrade your rails up to 4 (or whatever version this method was introduced.)

Cannot get my Articles controller to create a blog Article with a picture. I am using imagemagick and carrierwave

My create action in ArticlesController seems fine if I create an Article without uploading a picture. However, if I try to upload a picture for an article, I get the error:
ActionController::UrlGenerationError in ArticlesController#create
No route matches {:action=>"show", :controller=>"articles", :id=>nil} missing required keys: [:id]
Here is my Articles controller:
class ArticlesController < ApplicationController
before_filter :require_login, only: [:new, :create, :edit, :update, :destroy]
def index
#articles = Article.all
end
def show
#article = Article.find(params[:id])
#comment = Comment.new
#comment.article_id = #article.id
end
def new
#article = Article.new
end
def create
#article = Article.new(article_params)
#article.save
redirect_to article_path(#article)
end
def edit
#article = Article.find(params[:id])
end
def destroy
#article = Article.find(params[:id])
#article.destroy
redirect_to articles_path
end
def update
#article = Article.find(params[:id])
#article.update(article_params)
flash.notice = "Article '#{#article.title}' Updated!"
redirect_to article_path(#article)
end
private
def article_params
params.require(:article).permit(:title, :body, :tag_list, :picture)
end
end
Here is my Article model:
class Article < ActiveRecord::Base
has_many :comments
has_many :taggings
has_many :tags, through: :taggings
mount_uploader :picture, PictureUploader
validate :picture_size
def tag_list
self.tags.collect do |tag|
tag.name
end.join(", ")
end
def tag_list=(tags_string)
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by(name: name) }
self.tags = new_or_found_tags
end
# Validates the size of an uploaded picture.
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
My Gemfile :
source 'http://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.8'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'carrierwave', '0.10.0'
gem 'mini_magick', '~> 4.0.4'
gem 'fog', '~> 1.27.0'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
gem 'sorcery'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin]
And finally my picture uploader:
# encoding: utf-8
class PictureUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
process resize_to_limit: [500, 500]
if Rails.env.production?
storage :fog
else
storage :file
end
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :resize_to_fit => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
What am I doing wrong with carrierwave and Imagemagic to get
this error ?

ActiveAdmin ForbiddenAttributesError

i am a brand new for Ruby on Rails.
I am using a ActiveAdmin and i have a problem with creating a AdminUser
ActiveModel::ForbiddenAttributesError in Admin::AdminUsersController#create
ActiveModel::ForbiddenAttributesError
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"nvV++6GNTdA/nDzw1iJ6Ii84pZPcv2mzg0PK2Cg9Ag0=",
"admin_user"=>{"email"=>"admin2#example.com"},
"commit"=>"Create Admin user"}*
Rails 4.1.0
activeadmin 1.0.0
ruby 2.1
app/admin/admin_user.rb
ActiveAdmin.register AdminUser do
index do
column :email
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
default_actions
end
form do |f|
f.inputs "Admin Details" do
f.input :email
end
f.actions
end
end
app/models/admin_user.rb
class AdminUser < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
after_create { |admin| admin.send_reset_password_instructions }
def password_required?
new_record? ? false : super
end
end
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.1.0'
gem 'sqlite3'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'activeadmin', github: 'gregbell/active_admin'
gem 'polyamorous', github: 'activerecord-hackery/polyamorous'
gem 'ransack', github: 'activerecord-hackery/ransack'
gem 'formtastic', github: 'justinfrench/formtastic'
gem 'devise'
gem 'sdoc', '~> 0.4.0', group: :doc
config/environments/development.rb
Rails.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 web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
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
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Sending emails works
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end
Rails 4 uses strong parameters, which moves attribute whitelisting from the model to the controller. It is necessary to specify the attributes that you would like to be saved in the database. You have not permitted the attributes in your code, which is why you are receiving the ActiveModel::ForbiddenAttributesError.
Refer to the documentation of ActiveAdmin : Setting up Strong Parameters
You can setup strong parameters in the following way, using permit_params method which creates a method called permitted_params, use this method when overriding create or update actions:
ActiveAdmin.register AdminUser do
## ...
permit_params :attr1, :attr2 ## Add this line
end
Replace :attr1, :attr2, etc with the actual attribute names that you want to whitelist. For example: :email
What you're seeing is a security feature of newer versions of Rails. You will have to create a whitelist for the attributes which can be updated by the params as entered by the user. Otherwise, you will have to set each value manually.
Here's a sample of whitelisting certain params:
ActiveAdmin.register Post do
permit_params :title, :content, :publisher_id
end
See the ActiveAdmin docs on the subject:
https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters

MongoId - uninitialized constant App::Mongo (NameError)"

In Sinatra app I have
#config.rb
require 'mongoid'
class App
configure do
Mongoid.configure do |config|
name = "my_db"
host = "localhost"
config.master = Mongo::Connection.new.db(name)
config.slaves = [Mongo::Connection.new(host, 27017, :slave_ok => true).db(name)]
config.persist_in_safe_mode = false
end
end
end
#Gemfile
gem "mongoid", "~> 3.0.0"
gem "bson_ext"
and it gives me an error "`const_missing': uninitialized constant App::Mongo (NameError)"
How do I fix it?
This is due to the fact that Mongoid 3.x no longer uses the 10Gen Ruby driver so Mongo module will not be loaded by require 'mongoid'. You need to use the new Mongoid.load! method. You may have to change your config.yml file a bit as the syntax has changed. Please see http://mongoid.org/en/mongoid/docs/installation.html

Resources