ActiveResource model is not getting initialized - ruby-on-rails

I am looking at using ActiveResource but is now facing a problem that I am unable to figure out myself (was searching the net for a couple of days for the solution by now).
So I have an authentication app sitting at http://localhost:80 and a client on port :85
In my auth app
I have a User model with its controller which follows REST architecture and is set to respond to xml calls.
Here is what I have in my auth app:
models/User.rb
class User < ActiveRecord::Base
end
*controllers/users_controller.rb*
class UsersController < ApplicationController
respond_to :html, :xml, :js
def index
#users = User.find :all
respond_with #users
end
def show
#user = User.find(params[:id])
respond_with #user
end
.
.
.
end
In a client application
I have a class extending from active resource as follows:
models/user.rb
class User < ActiveResource::Base
self.site = "http://localhost:80"
end
Here is how I am trying to use it:
*controllers/sessions_controller.rb*
class SessionController < ApplicationController
def home
#user = User.find(:all)
end
end
what could go wrong, right?..
But then I am getting the following error:
Started GET "/" for 127.0.0.1 at 2013-09-02 08:33:44 +1200 Processing
by SessionsController#home as HTML Completed 500 Internal Server Error
in 3ms
NameError (uninitialized constant ActiveResource):
app/models/user.rb:1:in <top (required)>'
app/controllers/sessions_controller.rb:4:inhome'
Rendered
/usr/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_source.erb
(1.6ms) Rendered
/usr/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb
(2.7ms) Rendered
/usr/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
(2.2ms) Rendered
/usr/lib/ruby/gems/1.9.1/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (37.4ms)
I am using:
ruby 1.9.3p0 (2011-10-30 revision 33570) [i686-linux]
Rails 4.0.0
activeresource (4.0.0) gem is installed
What could I possibly be doing wrong?
Is it possible that ActiveResource failing to connect to localhost:80 and as a result does not get initialized?
EDIT:
done rvm use 2.0.0 so now ruby version is: ruby 2.0.0p247 (2013-06-27 revision 41674) [i686-linux]
EDIT:
RubyGems Environment:
- RUBYGEMS VERSION: 2.0.7
- RUBY VERSION: 1.9.3 (2011-10-30 patchlevel 0) [i686-linux]
- INSTALLATION DIRECTORY: /usr/lib/ruby/gems/1.9.1
- RUBY EXECUTABLE: /usr/bin/ruby1.9.1
- EXECUTABLE DIRECTORY: /usr/bin
- RUBYGEMS PLATFORMS:
- ruby
- x86-linux
- GEM PATHS:
- /usr/lib/ruby/gems/1.9.1
- /home/dmitry/.gem/ruby/1.9.1
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :backtrace => false
- :bulk_threshold => 1000
- REMOTE SOURCES:
- https://rubygems.org/

I have finally figured this out...
For some reason (I would be grateful if someone can post an explanation why) I had to require active resource manually in my user.rb file.
The correct code to make it work should be:
require 'active_resource'
class User < ActiveResource::Base
self.site = "http://localhost:80"
end
P.S
Thank you zeantsoi for your comments, those have led me into a search for reasons of this gem not being loaded.

In your Gemfile add the activeresource gem like so:
gem 'activeresource', require: 'active_resource'
This will make it behave as it should - without having to require it at the beginning of every activeresource model.

ActiveResource should be loaded in your config/application.rb file:
# config/application.rb
# Pick the frameworks you want:
require 'active_resource/railtie'
require "action_controller/railtie"
...
In this case you will be able to configure ActiveResource later in the same file, for example:
# config/application.rb
module TestClient
class Application < Rails::Application
config.active_resource.include_format_in_path = false
config.active_resource.site = "http://localhost:80"
...
This is handy if you want to set some default options for all your ActiveResource models and of course you can override any of these options for some specific model:
# app/models/user.rb
class User < ActiveResource::Base
self.include_format_in_path = true # append .json at the end of url
end

Related

Ruby gem, undefined method `ruby gem name' for Model (call 'Model.connection' to establish a connection):Class)

I'm creating a ruby gem with rails 6. This is my main ruby gem file:
#lib/ruby_gem_name.rb
require 'active_support'
require 'active_record'
require 'ruby_gem_name/version'
require 'ruby_gem_name/class_methods'
# frozen_string_literal: true
puts 'The gem was loaded'
module RubyGemName; end
This is lib/ruby_gem_name/class_methods.rb
module RubyGemName
module ClassMethods
def self.ruby_gem_name_class_method
puts 'Hello'
end
end
extend ClassMethods
end
i enter in irb console and i can see:
ruby-gem-name$ irb
2.7.1 :001 > require 'ruby-gem-name'
The gem was loaded
=> true
2.7.1 :002 > RubyGemName::ClassMethods.ruby_gem_name_class_method
Hello
=> nil
Now....I've added my gem to the gemfile in my rails project:
gem 'ruby_gem_name', path: 'path_to_ruby_gem_name'
I can see the installed gem in Gemfile.lock:
PATH
remote: 'path_to_ruby_gem_name'
specs:
ruby_gem_name (0.1.0)
activerecord (~> 6)
activesupport (~> 6)
rails (~> 6)
GEM
remote: https://rubygems.org/
specs:
actioncable (6.0.3.5)
actionpack (= 6.0.3.5)
Now, i want to use this class method in models of my rails project:
i have this code:
class Cart < ApplicationRecord
extend RubyGemName::ClassMethods
end
and when i try to use this class method from my rails project console, i see:
shopping-cart$ bundle exec rails c
Running via Spring preloader in process 32494
Loading development environment (Rails 6.0.3.5)
2.7.1 :001 > Cart.ruby_gem_name_class_method
Traceback (most recent call last):
1: from (irb):1
NoMethodError (undefined method `ruby_gem_name_class_method' for Cart (call 'Cart.connection' to establish a connection):Class)
In order to use the method ruby_gem_name_class_method as a class method you need to use extend as eugen points out in their example. If you use extend then the Module's methods are already Class methods, therefore the self on your ruby_gem_name_class_method is redundant.
Your module's code should change to this:
module RubyGemName
module ClassMethods
def ruby_gem_name_class_method
puts 'Hello'
end
end
end
The other approach is to use include which will make the Module's methods available on the instance of the Class and you can achieve this by modifying your Class:
class Cart < ApplicationRecord
include RubyGemName::ClassMethods
end
and then instantiate the object and call the instance method:
Cart.new.ruby_gem_name_class_method
You can omit self on the Module's method as it refers to the newly created instance.
You'll probably want to use extend instead of include, as in
class Cart < ApplicationRecord
extend RubyGemName::ClassMethods
end
extend will add the methods from RubyGemName::ClassMethods, as opposed to include, which will add them as instance methods.
For a more detailed explanation of extend vs. include, see https://stackoverflow.com/a/5008349/163640

ENOENT Error in Serializer

I have just started working with rails and I encountered this error which does not give a lot of detail. Since I am not familiar with ruby on rails, perhaps someone here can help.
The error occurs in the active model serializer for the model.
class SecuritySerializer < ActiveModel::Serializer
attributes :id, :name, :ticker, :identifier, :weight
end
the rendering occurs as follows:
def index
#securities = Security.all
render(json: #securities, each_serializer: SecuritySerializer)
end
The error that I get:
Errno::ENOENT (No such file or directory # rb_sysopen - C):
app/serializers/security_serializer.rb:1:in `<top (required)>'
app/controllers/securities_controller.rb:9:in `index'
EDIT
I am using 64-bit ruby on windows 8.
I added this to a file called serializer_init.rb in config/initializers
ActiveModel::Serializer.config.adapter = :json_api
I was using version 0.10.0. I downgraded to 0.8.0 and removed the initializer. This solved the issue.
User gem from branch master.
gem 'active_model_serializers', :git => 'git://github.com/rails-api/active_model_serializers.git'

webdriver-user-agent gem classes not included in Rails model

When I try to use the webdriver-user-agent gem, I cannot access the module, let alone its methods.
in Rails.root/Gemfile.lock:
GEM
remote: https://rubygems.org/
specs:
# ...
watir-webdriver (0.6.10)
selenium-webdriver (>= 2.18.0)
webdriver-user-agent (7.1)
facets
json
selenium-webdriver
# ...
in Rails.root/app/models/some_model.rb:
class SomeModel < ActiveRecord::Base
def some_function
driver = WebDriver::UserAgent.driver(browser: :firefox, agent: :iphone, orientation: :portrait)
# other functionality ...
end
end
Load environment
rails c
Using the class:
2.0.0-p353 :001 > s = SomeModel.last
2.0.0-p353 :002 > s.some_function
NameError: uninitialized constant SomeModel::WebDriver
Is Rails looking for the Module in the wrong place by looking for it within SomeModel? Am I accessing this incorrectly? The module not is available:
2.0.0-p353 :003 > Webdriver::UserAgent
NameError: uninitialized constant WebDriver # corrected on edit
I've tried including require 'webdriver-user-agent' at the top of the class file, and then include WebDriver -- same error, but on loading of the model instance.
I filed a bug report in the repo, but I'm sure I'm doing something dumb here...
Additional info:
Centos 6.5
Rails 4.1.4
Ruby 2.0
Rubygems 2.2.2
You are trying to look for the module:
WebDriver
However, the webdriver-user-agent gem uses the module:
Webdriver
Notice the difference in the lowercase 'd'. Class and module names are case-sensitive, which is why the constant is not being found.
The function should work by correcting the module name:
class SomeModel < ActiveRecord::Base
def some_function
driver = Webdriver::UserAgent.driver(browser: :firefox, agent: :iphone, orientation: :portrait)
# other functionality ...
end
end

mail_room with Ruby on Rails

I can't seem to get mail_room working in a Rails app.
When testing the logger delivery method, it works correctly with this
config/mail_room.yml
---
:mailboxes:
-
:email: "some#gmail.com"
:password: "password"
:name: "inbox"
:delivery_method: logger
:log_path: "email.log"
but the postback delivery method doesn't seem to work at all
config/mail_room.yml
---
:mailboxes:
-
:email: "some#gmail.com"
:password: "password"
:name: "inbox"
:delivery_method: postback
:delivery_url: "http://global-or-local-ip/inbox"
:delivery_token: "abcdefg"
config/routes.rb
post 'inbox', :to => 'users#inbox', :as => :users_inbox
app/controllers/users_controller.rb
class UsersController < ApplicationController
def inbox
puts "Check your inbox..."
end
end
Not sure if it's because of mail_room or something missing from the Rails app. I've tried different verbs in the routes. Using Rails 4.0.2 and tried both 0.1.0 and github source for the gem.
After some research, we found that Faraday 0.8.8 was having some issues with ruby 2.0 as we were using it in mail_room. Released a new gem, and made notes in the README that users should install >= 0.8.9 of Faraday.

Why is this line breaking Rails with Passenger on DreamHost?

Ok, so I have a Rails app set up on DreamHost and I had it working a while ago and now it's broken. I don't know a lot about deployment environments or anything like that so please forgive my ignorance. Anyway, it looks like the app is crashing at this line in config/environment.rb:
require File.join(File.dirname(__FILE__), 'boot')
config/boot.rb is pretty much normal, but I'll include it here anyway.
# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
module Rails
class << self
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exist?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
Rails::Initializer.run(:install_gem_spec_stubs)
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
gem 'rails', version
else
gem 'rails'
end
rescue Gem::LoadError => load_error
$stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
exit 1
end
class << self
def rubygems_version
Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
def load_rubygems
require 'rubygems'
min_version = '1.1.1'
unless rubygems_version >= min_version
$stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
$stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end
# All that for this:
Rails.boot!
Does anyone have any ideas? I am not getting any errors in the log or on the page.
-fREW
I had the same problem on DreamHost. Freezing rails and unpacking all gems got me past it.
rake rails:freeze:gems
rake gems:unpack:dependencies
My guess would be that you're breaking because of a newer version of the Rails gems on Dreamhost. At least, that's been my issue when things have blown up in something like boot.rb.
Try freezing the gems from your development environment into your vendor/rails directory.
Ya - the problem is not really in boot.rb - it's just that boot.rb is where rails is actually loaded.
So you'll get an error like this if you've specified a version of Rails that just doesn't exist on your dreamhost slice. This can happen if you either upgrade your project, start a new project (and forget that you upgraded rails in the meanwhile) or if you're still using an old version of rails and it's now been removed from the dreamhost server that you're on.
To figure out which is is, look in config/environment.rb for the line that'll read something like:
RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION
Then ssh to your dreamhost server and type gem list and see if your version is in the list.
If not, you an try several options. Lets say the version you're using is 2.3.4
To begin with, try: gem install rails -v=2.3.4 then restart. That may be all that is required.
If that doesn't work, then try freezing and unpacking the gems (as per the other answer here).
There is also another possibility - that you're actually missing a gem that rails depends on but which is failing silently - eg a dependency on a certain version of rack caught me out once. But you may also have other gem dependencies
If you run rake gems you will be able to list all the gems that your project knows about that it needs - make sure they're installed to begin with.
Then, as a sort of rough smoke-test, try running script/console - if you're missing an important rails gem, script/console won't load and should fail, giving you a notice about the gem you need.
Update:
If you're trying to run v 2.3.5, you may also be suffering from this problem:
Bypassing rack version error using Rails 2.3.5
In which case you'll need to follow the instructions there.

Resources