Garb just stopped working in Rails 3 without being touched - ruby-on-rails-3

I have a Garb model:
class Visits
extend Garb::Model
metrics :visits, :new_visits, :pageviews
dimensions :month, :hostname, :network_domain, :country, :region, :source
end
And I have this line in my controller:
for visit in Visits.results(profile, :start_date => (Date.today-numdays), :filters => { :hostname.eql => "#{#brand.subdomain}.mysite.com" })
This has worked fabulously. But all of a sudden, even though none of the actual code has been modified:
NoMethodError in AnalyticsController#index
undefined method `eql' for :hostname:Symbol
What could be causing this?

For some reason the garb/lib/support.rb is not loaded anymore. Did you put :require => false to the garb gem line in Gemfile?

Did you install right_http_connection-1.3.0 gem? It will cause the garb/lib/support.rb not to be loaded if you require 'right_http_connection' before 'garb'. If that you could fix this by installing a lower right_http_connection, such as right_http_connection-1.2.4.
After all you can use command
find /Your/gems/installed/dir -name "*.rb" -print | xargs grep '\<support\>' | grep 'require'
to find what files cause your garb/lib/support.rb was not loaded anymore.
This link http://kayakjang.github.com/2011/05/27/garb.html may be helpful to you for this problem.

I fixed this by cutting and pasting the contents of garb/lib/support.rb into the environment.rb file. Not ideal, I know. But I don't know what gem update modified Symbol, and this works. Props to Roman for pointing me in the right direction.

Related

Devise Parameter Sanitizer "For" Method Not Found Rails 5

I have just added devise to my shiny new Rails 5 app. All's good and dandy until I try to add a username to the Devise user model. Everything worked until I ran it and went to localhost:3000/users/sign_up, where I was greeted by this error:
undefined method `for' for #<Devise::ParameterSanitizer:0x007fa0dc31c1b0> Did you mean? fork
I have searched the wonderful place of Google for any results, only being given outdated, Rails 4 errors and solutions, the same with searching Stack Overflow itself. I cannot get my mind to find a working solution. I would appreciate help very much. Here is how I prepared for this:
Create the migration: rails generate migration add_username_to_users username:string:uniq
Migrate the database rake db:migrate
Add strong parameters to the application controller devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(..) }
Add username parameters to the Devise views
Restart the server
Is there anything I missed or did wrong?
The .for method is deprecated, from devise 4.1+ .permit method is available
Try .permit. It should work.
devise_parameter_sanitizer.permit(:my_action) { |u| u.permit(..) }
Hope this will help you :)
The problem was well mentioned by #Shadow but this syntax worked for me:
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :email])
devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :phone, :email, bank_attributes:
[:bank_name, :bank_account]])
end

sinatra-authentication routes not found

I'm trying to add the sinatra-authentication gem to a Sinatra app, and while it's in there and doing part of its thing, for some reason the routes are seemingly not getting added. The code basics:
require 'sinatra'
require 'digest/sha1'
require 'rack-flash'
require 'mongo_mapper'
require 'sinatra-authentication'
MongoMapper.connection = Mongo::Connection.new('127.0.0.1', 27017, :pool_size => 5, :pool_timeout => 5)
MongoMapper.database = 'cms'
module CmsMod
class CmsApp < Sinatra::Base
use Rack::Session::Cookie, :secret => 'something secret'
use Rack::Flash
get '/' do
#redirect to('/list') # commented out for testing
end
get '/private' do
login_required
'Protected Page'
end
And then the rest of things. The symptoms are that pointing the browser to my normal routes works fine. Going to '/private' does the redirect to '/login' properly, but I get the old "Sinatra doesn't know this ditty" message; same if I try to visit '/login' directly. I tried using 'binding.pry' to inspect things inside a get block and from what I could tell the routes aren't there. Any ideas about what could cause this would be really appreciated.
Having looked at the library's source, it's written as an extension but the examples and docs don't mention how the extension is registered. Try this:
module CmsMod
class CmsApp < Sinatra::Base
register Sinatra::SinatraAuthentication # <= this is the missing magic line.
then the routes should appear. As an aside, I'd also suggest using the encrypted_cookie gem.
use Rack::Session::Cookie, :secret => 'something secret'
becomes:
use Rack::Session::EncryptedCookie, :secret => 'something secret'
seems like it requires 'haml' gem as well, so if you are not using haml (like I'm using slim), you should include haml in your project for it to work, what a pain!!
Also remember to set layout in your view, because by default it will be looking for views/layout.haml

Thinking sphinx not indexing belongs_to relationship properly in production but works fine in dev

I want to display the movies associated to a given author. On the author's page, I want users to be able to paginate, sort, and filter by keyword.
Everything works fine on my local machine. But, in production, the list of movies on the author's page is empty, and I can't figure out why. In production, in the console, I tested the following expressions, but no luck (always returns 0, while it returns values > 0 in dev):
ruby-1.9.2-p290 :042 > Movie.search(:with => {:author_ids => [6]}).count
=> 0
ruby-1.9.2-p290 :043 > Movie.search(:with => {:author_ids => 6}).count
=> 0
The weird thing is that I'm using a very similar code to display the movies associated to a topic on a topic's page, and it works great in development AND in production. For instance:
ruby-1.9.2-p290 :051 > Movie.search(:with => {:topic_ids => 2}, :per_page => 1000).count
=> 295
Here is how I define my Movie class:
class Movie < ActiveRecord::Base
belongs_to :author
has_many :topics
...
define_index('movie') do
...
has author(:id), :as => :author_ids,
:facet => true
has topics(:id), :as => :topic_ids,
:facet => true
...
end
...
end
And here is what my Author show controller looks like:
def show
#author = Author.find(params[:id])
keywords = params[:what] || ""
with_params[:author_ids] = [#author.id]
#movies = Movie.search(
keywords,
:with => with_params
)
end
This leads me to believe there is something wrong with the Sphinx index in production, but I'm not sure how to investigate further to find the root of the problem...
UPDATE: Following Pat's suggestion, I updated Sphinx and everything was solved (I upgraded from 0.9.8 to 0.9.10)! I was confused because Sphinx is NOT a Gem (even though a Sphinx gem exists)... So I had to go through the regular download, make, make install process.
I'll start with the obvious, but maybe this has already been tried - is the author_ids attribute something relatively new? Have you rebuilt (indexed and restarted) Sphinx since adding that attribute? rake ts:rebuild is the easy way to do that.
Update: It turns out updating Sphinx was the fix here - Alex can confirm which version, but I'm guessing 0.9.9 or better should do the trick.

rails3-amf - to_amf method not found on ActiveRecord objects

I am using the rails3-amf gem by warhammerkid in my Rails 3 / Flex 4 project.
AFAIK, I have correctly followed the "Getting Started" instructions from the GitHub page.
I have added the gem lines to my Gemfile.
I have installed the gems using bundle install.
From my Flex application, I will be making the RemoteObject call to the index action in the ManageMySchool::GradesController file. This is the code in the app/controllers/manage_my_school/grades_controller.rb file:
class ManageMySchool::GradesController < ApplicationController
respond_to :html, :amf
def index
#grade = Grade.first
respond_with(#grade) do |format|
format.amf { render :amf => #grade.to_amf }
end
end
end
The name of the model which is to be serialized is called Grade in both the Rails project (app/models/Grade.rb) and the Flex project (Grade.as with a RemoteAlias set as Grade). In the config/application.rb file, I have done the class mapping this way:
config.rails3amf.class_mapping do |m|
m.map :as => 'Grade', :ruby => 'Grade'
end
And I have done a parameter mapping this way:
config.rails3amf.map_params :controller => 'ManageMySchool::GradesController', :action => 'index', :params => [:authenticity_token]
Problem
Now, when I run the server and make the RemoteObject call from Flex, I get a to_amf undefined method error for the Grade model.
If I change Grade.first to Grade.all, #grade would have an array of Grades. But the undefined method error message still mentions the Grade model. This means that the to_amf method is working for the Array class but not for the ActiveRecord model.
Why is this? What am I doing wrong?
Is there something I have to do to "enable" the rails3-amf gem for ActiveRecord models?
I would appreciate any insights. Thanks!
Update
#warhammerkid: Here is the output of Grade.ancestors as seen in rails console.
ree-1.8.7-2011.03 :006 > puts Grade.ancestors
Grade
ActiveRecord::Base
Paperclip::CallbackCompatability::Rails3::Running
Paperclip::CallbackCompatability::Rails3
Paperclip::Glue CanCan::ModelAdditions
Authlogic::ActsAsAuthentic::ValidationsScope
Authlogic::ActsAsAuthentic::SingleAccessToken
Authlogic::ActsAsAuthentic::SessionMaintenance
Authlogic::ActsAsAuthentic::RestfulAuthentication::InstanceMethods
Authlogic::ActsAsAuthentic::RestfulAuthentication
Authlogic::ActsAsAuthentic::PersistenceToken
Authlogic::ActsAsAuthentic::PerishableToken
Authlogic::ActsAsAuthentic::Password
Authlogic::ActsAsAuthentic::MagicColumns
Authlogic::ActsAsAuthentic::Login
Authlogic::ActsAsAuthentic::LoggedInStatus
Authlogic::ActsAsAuthentic::Email
Authlogic::ActsAsAuthentic::Base
ActiveRecord::Aggregations
ActiveRecord::Transactions
ActiveRecord::Reflection
ActiveRecord::Serialization
ActiveModel::Serializers::Xml
ActiveModel::Serializers::JSON
ActiveModel::Serialization
ActiveRecord::AutosaveAssociation
ActiveRecord::NestedAttributes
ActiveRecord::Associations
ActiveRecord::AssociationPreload
ActiveRecord::NamedScope
ActiveModel::Validations::Callbacks
ActiveRecord::Callbacks
ActiveModel::Observing
ActiveRecord::Timestamp
ActiveModel::MassAssignmentSecurity
ActiveRecord::AttributeMethods::Dirty
ActiveModel::Dirty
ActiveRecord::AttributeMethods::TimeZoneConversion
ActiveRecord::AttributeMethods::PrimaryKey
ActiveRecord::AttributeMethods::Read
ActiveRecord::AttributeMethods::Write
ActiveRecord::AttributeMethods::BeforeTypeCast
#<Module:0x1028356f0> ActiveRecord::AttributeMethods::Query
ActiveRecord::AttributeMethods
ActiveModel::AttributeMethods
ActiveRecord::Locking::Optimistic
ActiveRecord::Locking::Pessimistic
ActiveRecord::Validations
ActiveModel::Validations::HelperMethods
ActiveModel::Validations
ActiveSupport::Callbacks
ActiveModel::Conversion
ActiveRecord::Persistence Object
PP::ObjectMixin Base64::Deprecated
Base64
ActiveSupport::Dependencies::Loadable
Kernel
Note that only ActiveModel::Serialization is there. No mention of Rails3AMF.
Does this mean I have to do something special to load the Rails3AMF module for the ActiveRecord models?
I am using Rails 3.0.5 with the latest version of ree. The gems are all contained in a gemset managed using rvm.
Update 2
If I remove the to_amf in the render :amf line, then I get the following error:
Grade Load (0.3ms) SELECT `grades`.* FROM `grades` LIMIT 1
Completed 200 OK in 195ms (Views: 0.1ms | ActiveRecord: 0.8ms)
Sending back AMF
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.last):
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.8ms)
Rendered /Users/anjan/.rvm/gems/ree-1.8.7-2011.03#rb/gems/actionpack-3.0.5/lib/> > action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (13.6ms)
Started POST "/amf" for 127.0.0.1 at Fri Apr 15 17:03:34 +0530 2011
Sending back AMF
Update 3
If I manually add the line include Rails3AMF::Serialization at the top of the Grade.rb model file, then it all works. So, does this mean that I have to put this line in all my models?
I see that this is already being done in line numbers 40 - 42 in the lib/rails3-amf/serialization.rb file of the gem:
# Hook into any object that includes ActiveModel::Serialization
module ActiveModel::Serialization
include Rails3AMF::Serialization
end
Why isn't this working? Should I force-load the gem when my application initializes or something?
Thanks!
Update 4 - Solved by this workaround
Okay, I just ended up adding this code block in an initializer:
class ActiveRecord::Base
include Rails3AMF::Serialization
end
And it is working.
#warhammerkid - Thanks for the help.
Rails3AMF::Serialization, the module that adds the to_amf method, is included in ActiveModel::Serialization when Rails3-AMF loads. If it's somehow not being included even though the code is running and ActiveModel::Serialization is one of your model's ancestors, then the simplest solution is just to add "include Rails3AMF::Serialization" at the top of your model implementation. I've never tried gem sets before, but it might be an issue with them, as everything works correctly using Bundler.
As an aside, feel free to post a bug to https://github.com/warhammerkid/rails3-amf/issues.

RSpec: simplest test fails with error: Expected block to return true value

I'm testing the waters with Rails and I'm stuck with this simple test:
I have this code in spec/routing/routing_spec.rb
require 'spec_helper'
describe "Accessing the root domain" do
it "should route to home#index" do
{ :get => '/' }.
should route_to(:controller => 'home', :action=>'index')
end
end
This fails with the following error:
Failure/Error: { :get => '/' }.
Expected block to return true value.
# ./spec/routing/routing_spec.rb:7:in `block (3 levels) in <top (required)>'
What's wrong in my code?
I ran into this opaque error message as well with Rails 3 and Ruby 1.9.2. The reason in my case was that I was using an old version of minitest that ships with Ruby, and in that version the assert_block method (invoked by assert_recognizes in ActionDispatch::Assertions::RoutingAssertions) does not display the error message (how the routing params didn't match). The fix for me was to add minitest to my Gemfile and install it via bundler:
group :test do
gem "minitest", ">= 2.6.1" # The minitest version that ships with Ruby is old and has bugs
end
I would then get a more understandable error message:
The recognized options <{"action"=>"index",
"controller"=>"publish/product_versions",
"product_id"=>"ipad_app"}> did not match <{"controller"=>"publish/product_versions",
"action"=>"indexx",
"product_id"=>"ipad_app"}>, difference: <{"action"=>"indexx"}>.
Expected block to return true value.
This seems like it should work, so my guess would be that there is a configuration problem. Difficult to know what it is, though, without seeing more of the app. Also, the failure says it happens on line 7, but it references line 5 in the code above, so there might be something else in the file that is gumming up the works.
Also, the error message is confusing because the expectation is written on two lines. If you wrote it on one line, you'd see the whole statement. Not that that would help narrow down this problem, other than to help you understand that it's not trying to treat { :get => '/' } as a block.
HTH,
David
This happened with me because my controller rendered the wrong view. I fixed the logic of my controller method and everything worked fine.