(Rails) : NoMethodError: undefined method cost' for BCrypt::Engine:Class - ruby-on-rails-4

When I learn "Ruby on Rails Tutorial", and I want to create a User on console:
irb(main):001:0> User.create(name:"gsky",email:"k#q.com",
irb(main):002:1* password:"aaaaaa",password_confirmation:"aaaaaa")
then, I getting the following error message:
NoMethodError: undefined method cost' for BCrypt::Engine:Class
from D:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activemodel-4.
0.2/lib/active_model/secure_password.rb:104:inpassword='
from D:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4
.0.2/lib/active_record/attribute_assignment.rb:42:in public_send'
This is user model:
class User < ActiveRecord::Base
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,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
end

Add bcrypt-ruby to your Gemfile as specified below:
gem 'bcrypt-ruby', '3.1.2'
then run bundle update from your project root directory and bundle install

When i saw "Ruby On Rails Tutorial" I have met the same problem,
I solved it by set Gemfile from:
gem 'bcrypt-ruby', '3.0.1'
to:
gem 'bcrypt-ruby', '3.1.2'
then run:
bundle install

Also going for the tutorial/book and having the same problems, I used gem 'bcrypt-ruby', '~> 3.0.0' because of problems with bundle install. After going through secure_password.rb, the problem was in BCrypt::Engine.cost, this method actually doesn't exist.
I changed my gem to gem 'bcrypt-ruby', '~> 3.1.0' which installed bcrypt 3.1.7. Saw a warning message about the gem being renamed and changed it to gem 'bcrypt', '~> 3.1.0' (this part shouldn't matter). After doing bundle install, I was able to see the implementation of Bcrypt::Engine.cost through my IDE and I was able to make my user in rails c.
I want to add that adding ActiveModel::SecurePassword.min_cost = true in test.rb was able to let me make new users if I ran rails c in test environment, but when I added the same line in development.rb, it didn't work.

I think you are learning rails from the tutorial. If you just want to continue and not spent much time on doing the right fix, you can just use the cost as say 10, instead of calling the BCrypt::Engine.cost method.
So replace
cost = BCrypt::Engine.cost
with
cost = 10
This value when used will take less than 200ms to compute and that should be okay.

Tested on mac:
Include this in your gemfile:
gem 'bcrypt', '3.1.11'
run:
xcode-select --install
then run: bundle install
That's it.
Best of lucks

Related

Capybara::Poltergeist Status error, failed to reach server

I am trying to make some tests with Rspec/Capybara/Poltergeist on my Rails 4 application, Phantomjs is installed (version 2.2.1), but I always get this error :
Failure/Error: visit(perfect_landing_page_path)
Capybara::Poltergeist::StatusFailError:
Request to 'http://127.0.0.1:49623/path' failed to reach server, check DNS
and/or server status
The test i'm working on :
require 'rails_helper'
RSpec.feature 'Subscription', :type => :feature do
let!(:plan) { create(:plan) }
let!(:landing_page) { create(:landing_page) }
before(:each) { landing_page.default_plan = plan }
describe 'landing_page#perfect_show' do
scenario 'form display', js: true do
plan_2 = create(:plan)
plan_3 = create(:plan)
landing_page.plans << plan_2
landing_page.plans << plan_3
visit(perfect_landing_page_path)
expect(page).to have_css(".start-now", count: 3)
first(".start-now").click
expect(page).to have_css("#new_user")
end
end
end
My Gemfile looks like this :
gem 'rspec-rails', '~> 3.0'
gem 'factory_girl_rails'
gem 'guard-rspec'
group :test do
gem 'database_cleaner'
gem 'capybara'
gem 'capybara-screenshot'
gem 'poltergeist'
gem 'selenium-webdriver'
gem 'shoulda-matchers', require: false
gem 'show_me_the_cookies'
end
My spec/support/capybara.rb file :
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require "capybara/poltergeist" # Add this line to require poltergeist
require 'selenium-webdriver'
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, {:js_errors => false, :default_max_wait_time => 30, :timeout => 30, phantomjs_options: [
'--load-images=no',
'--ignore-ssl-errors=true',
'--ssl-protocol=any']})
end
Capybara.register_driver :poltergeist_debug do |app|
Capybara::Poltergeist::Driver.new(app, :inspector => true)
end
Capybara.configure do |config|
config.javascript_driver = :poltergeist
config.ignore_hidden_elements = true
config.default_max_wait_time = 30
end
My spec_helper.rb file :
require 'capybara/rspec'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
Did someone encounter this problem before ? Does anyone have a solution for this ? I have been banging my head for days looking on the web...
Thank you very much.
PS : it works fine on my friend's mac (Yosemite or El Capitan), just not on mine.
I was having this problem in CI (CodeShip).
Adding a call to bundle exec rake assets:precompile at the end of the setup commands seemed to fix it:
CodeShip CI Setup Commands:
rvm use 2.3.4 --install
bundle install
export RAILS_ENV=test
bundle exec rake db:schema:load
bundle exec rake assets:precompile
Also had a whitelist per #agbodike but in the rails_helper.rb
config.before(:each, js: true) do
page.driver.browser.url_whitelist = ["127.0.0.1"]
end
I had the same issue and it was due to a 3rd party script timing out. You can prevent loading of 3rd party scripts with a blacklist. For example:
config.before(:each, js: true) do
page.driver.browser.url_blacklist = ["http://use.typekit.net"]
end
would prevent any URL starting with http://use.typekit.net from being called for each test that uses the js driver. More information can be found at:
https://robots.thoughtbot.com/speed-up-javascript-capybara-specs-by-blacklisting-urls
Alternatively you can use a whitelist:
config.before(:each, js: true) do
page.driver.browser.url_whitelist = ["127.0.0.1"]
end
which will block all requests not to 127.0.0.1
I placed the configuration in spec/feature_helper.rb to ensure it was only set for feature specs.
You can avoid these by precompile the assets before tests.
And the code is:
RSpec.configure do |config|
config.before :all do
ENV['PRECOMPILE_ASSETS'] ||= begin
case self.class.metadata[:type]
when :feature, :view
STDOUT.write "Precompiling assets..."
require 'rake'
Rails.application.load_tasks
Rake::Task['assets:precompile'].invoke
STDOUT.puts " done."
Time.now.to_s
end
end
end
end
more info

No exception received from Rake task with Airbrake rails integration

Since version 5 Airbrake and its Rails integration offers automatic exception reporting in any Rake tasks.
However I've not received rake exception on my errbit server.
I've made the following test :
Create a fresh rails 4.1 application.
Include airbrake gem.
Create Airbrake initializer (used an errbit configuration).
Add a rake task which raises an exception.
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.1.6'
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 'sdoc', '~> 0.4.0', group: :doc
gem 'spring', group: :development
gem 'airbrake', '5.0.5'
initializers/airbrake.rb
Airbrake.configure do |config|
config.environment = Rails.env
config.host = 'https://xxxxxxxxxx.herokuapp.com/'
config.project_id = true
config.project_key = 'xxxxxxxxxxx'
config.ignore_environments = []
end
lib/rake/raise.rake
namespace :raise do
desc 'raise error'
task error: :environment do
1 / 0
end
end
I tried to execute the rake task rake raise:error and got the following backtrace:
rake aborted!
ZeroDivisionError: divided by 0
/Users/Yann/code/airbraker/lib/tasks/raise.rake:4:in `/'
/Users/Yann/code/airbraker/lib/tasks/raise.rake:4:in `block (2 levels) in <top (required)>'
/Users/Yann/.gem/ruby/2.2.2/gems/airbrake-5.0.5/lib/airbrake/rake/task_ext.rb:19:in `execute'
Tasks: TOP => raise:error
(See full trace by running task with --trace)
And never received any exception on my errbit server.
Note: execute rake airbrake:test sends an exception to my errbit server, I assume my configuration is correct.
Am I missing something ?
This is a minor bug. The problem is that Airbrake tries to be asynchronous and sometimes it doesn't work as expected. In this particular case the Ruby process quits before Airbrake sends your exception.
I've submitted a patch, which should fix this issue: https://github.com/airbrake/airbrake/pull/513

Rails + Mongoid + Strong Parms failure

So, I'm relatively new to ruby and rails. I'm playing around with mongoid for my database, though the only knowledge I hold is using active record.
I created a fresh project, being sure to skip active record so that I didn't have to perform the steps to remove it later in favor of mongoid.
I created a scaffold rails g scaffold user and went on my way looking around. So since I know that mongo is a schemaless db, I went to the model and modified it like so:
class User
include Mongoid::Document
include Mongoid::Timestamps
field :name, :type => String
end
pretty simple, just one field ( for now ). So, I added the field to my form via the normal route <%= text_field_tag :name %> and restarted my server rails s
I went to the dev site, and everything appears to work as it should. So, I submit the form and it submits. Looking at the DB, a document is created only without the name field. Remembering about strong attributes for active record, I went to the users_controller.rb and modified it like so:
def user_params
params.require(:user).permit(:name)
end
At this point, not remembering if I need to restart the server or not -- I do, just to be on the safe side. Once the server is running I go to the site, and submit the form and it tells me:
param is missing or the value is empty: user
Not sure what I've done wrong here, or if with mongoid I even need the .require line ( in all honesty I don't know what it does, except I thought it was requiring that these fields in permit are being submitted to the user model ) as removing the .require portion and just doing params.permit(:name) processes the information as it should.
$ ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]
$ rails --version
Rails 4.2.1
and my GemFile:
source 'https://rubygems.org'
gem 'rails', '4.2.1'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'mongoid', '~> 4.0.0'
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
#gem 'rspec-its'
# Use Unicorn as the app server
#gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
#gem 'font-awesome-rails', '~> 4.3.0.0'
#gem 'foundation-rails'
group :development, :test do
gem 'rspec-rails', '~> 3.2.1'
gem 'byebug'
gem 'web-console', '~> 2.0'
gem 'spring'
gem 'factory_girl_rails', '~> 4.5.0'
end
group :development do
gem 'quiet_assets', '~> 1.1.0'
end
group :test do
gem 'capybara', '~> 2.4.4'
gem 'capybara-email', '~> 2.4.0'
gem 'shoulda-matchers', '~> 2.8.0'
end
Any ideas of what I've done wrong? Only code associated with this is what was generated by rails new and rails g
First off you don't need to restart the rails server for any of the changes you've described.
The error you're getting just means that params[:user] is empty (or missing). If you check your development.log you'll see that params[:name] is set instead.
This is because you've used text_field_tag, which doesn't name the input so as to nest the value in params[:user].
Assuming you're using form_for to create your form, you want to instead do
f.text_field :name

Rails 4 assets not loading in heroku after 'rake assets:precompile'

This is driving me insane! My app works properly on the local server, but when I uploaded to heroku, the css and js files didn't update. I read to precompile using rake assets:precompile to fix the issue, but then I uploaded to heroku again and now all my assets aren't loading at all! I've tried all variations of precompile, installed 12factor gem, turned some config settings from false to true, still not happening! When i look at the console, it says
[Error] ReferenceError: Can't find variable: jQuery
global code (application-38ccb09605964287831a37a0d9faf188.js, line 1)
but I do have Jquery! it works fine on local! I dunno what I'm doing wrong guys.
Gemfile
gem 'bootstrap-sass-rails'
gem 'rails_12factor', group: :production
gem 'rails', '4.0.0'
gem 'sqlite3', :group => [:development, :test]
group :production do
gem 'thin'
gem 'pg'
end
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'jbuilder', '~> 1.2'
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
production.rb
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_assets = true
config.assets.js_compressor = :uglifier
config.assets.compile = true
config.assets.digest = true
config.assets.version = '1.0'
config.log_level = :info
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
running $RAILS_ENV=production bundle exec rake assets:precompile made my heroku app work now. so i guess problem is fixed..
sorry, I don't have an explanation on why it works
Simply run
$ bundle exec rake assets:precompile
$ git add .
$ git commit -am "assets precompiled locally"
$ git push heroku master

undefined local variable or method `acts_as_gmappable' for gmaps4rails

I am using gmaps4rails gem in my project for showing google maps on the forms but its showing
"undefined local variable or method `acts_as_gmappable' for gmaps4rails"
i am using rails 4.
gem 'gmaps4rails'
rails generate gmaps4rails:install
in model
acts_as_gmappable
def gmaps4rails_address
      address
end
Thanks,
im having the same issue as of 10/23/13
issue happens ONLY when deploy to Heroku; this works fine in my local environment
Gemfile contains:
...
gem 'rails', '4.0.0'
gem 'mysql'
gem 'haml'
gem 'paperclip'
gem 'gmaps4rails'
gem 'aws-s3'
gem 'aws-sdk'
gem 'stripe', :git => 'https://github.com/stripe/stripe-ruby'
gem 'will_paginate', '~> 3.0.5'
gem 'twilio-ruby'
gem 'json'
gem 'nokogiri'
gem 'rails_12factor', group: :production
...
already tried bundle install / bundle update & heroku restart
trace is as follows:
---> Preparing app for Rails asset pipeline
Running: rake assets:precompile
rake aborted!
undefined method acts_as_gmappable' for #<Class:0x007fa770b8ba68>
/tmp/build_94e76989-9e4f-4eef-8e2c-e31cd7d850c9/vendor/bundle/ruby/2.0.0/g ems/activerecord-4.0.0/lib/active_record/dynamic_matchers.rb:22:inmethod_missin g'
/tmp/build_94e76989-9e4f-4eef-8e2c-e31cd7d850c9/app/models/hay_shipper.rb: 4:in `'