Using ActiveRecord 3.1 without Rails in a script - ruby-on-rails

The following ought to work as a script, with ActiveRecord 3.1 (note that this is without Rails, not the other way around):
#!/usr/bin/env ruby
require "rubygems"
require "active_record"
dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)
irb
Unfortunately, it gives the error:
... connection_specification.rb:71:in `rescue in establish_connection': ...
Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter` ...
Adding the line gem 'mysql2', '<0.3' before require "active_record" as suggested by some previous posts (which reference 0.2.7, the 0.2 gem at the time; presently it's 0.2.18) doesn't change it.
How can I get it to work? I want ActiveRecord but not the whole of Rails.

Run in terminal
gem install mysql2
and add row to you code require 'mysql2'
#!/usr/bin/env ruby
require "rubygems"
require 'mysql2'
require "active_record"
dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)

This has fixed my issue, at least temporarily. I haven't yet restarted, so I don't know if it'll survive that. And it seems like a dirty hack; there's got to be a better way.
I haven't yet tested Aleksei's answer above, since I'm not having the same issue after having run this command. Will update ifwhen I do.
sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib ~/.rvm/gems/`rvm current`/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundle

Related

Why does Bundler.require not require dependencies?

I am developing a gem at the moment. Here's how the .gemspec looks like:
gem.add_dependency 'activerecord', '~> 4.2'
...
gem.add_development_dependency 'rails', '4.2.5'
...
and here's my Gemfile:
source 'https://rubygems.org'
gemspec
I am setting up my main file, lib/my_gem.rb like so:
module MyGem
module Lib
end
end
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
Bundler.require
However, if I start bundle console from my gem's folder, the dependencies are not required:
$ bundle console
Resolving dependencies...
irb(main):001:0> Rails
NameError: uninitialized constant Rails
...
irb(main):002:0> ActiveRecord
NameError: uninitialized constant ActiveRecord
...
What am I doing wrong?
I believe dependencies included via the gemspec command in the Gemfile are not automatically required by Bundler.require. Only gems listed directly in the Gemfile itself are.
Additionally, gems included in only certain Bundler groups, like 'development', may not be required by a Bundle.require even if they were included directly in the Gemfile, you need to tell bundler to require groups other than default.
You can always require gems manually though, like require 'rails'. Bundle.require doesn't do anything but require gem for each gem in your Gemfile (or at least default group in your Gemfile), it's doing any magic other than looking up all the gems in your Gemfile and requiring them. Bundle.require is considered by some to be a bad practice anyway, you should just require the dependencies you need in the files you need them, some say. Although Rails doesn't agree, and Rails apps have their own somewhat complicated way of auto-loading things.
But if you are in a Rails app, as your example dependencies suggest... why are you doing any require 'bundler/setup' or Bundle.require yourself at all though, instead of letting Rails boot process take care of it? Rails boot process will take care of requiring the Bundler groups you probably expect too (like the "development" group when in Rails.env == 'development').
You can use the bundler api yourself directly like you're doing, it's not too hard. But Rails ordinarily takes care of this for you, and if you are using Rails, rails probably already has done a Bundler.setup and Bundler.require as part of Rails boot process.

Ruby error: cannot load such file -- rest-client

I am using Ruby on Rails 4.
I am trying to
require 'rest-client'
in my controller so that I can parse the login information I am getting from a form and send it to an API.
I can verify that the gem is installed and is also in my Gemfile on the application root.
However, it is still throwing the "cannot load such file -- rest-client " when I try to require the file in my controller.
I have googled the error and most of the answers I saw were either the gem wasn't installed, wasn't in the Gemfile, or a combination of both those. Neither is the situation here.
Is my controller unable to access the rest-client gem for some reason? I have to use rest-client because it is required in the API.
This is the line I used to install the gem:
gem install rest-client
This is the homepage of the gem: https://github.com/archiloque/rest-client
Which just redirects you to https://github.com/rest-client/rest-client
I should also note that it works fine when I wasn't using the code in a Rails project but just running the commands in the Terminal.
Assuming you're using https://github.com/rest-client/rest-client (since you didn't specify), your require line should be
require 'rest-client'
according to the README. Also, make sure you restart your rails server after adding the gem to your Gemfile and running bundle.
Run the following command in your terminal:
gem install rest-client
and use require 'rest-client'. No need to change to rest_client.
in my case, none of the solutions in this thread worked
what did work, was to add the gem directly in the Gemfile:
gem 'rest-client'
after closing the rails server, exiting rails console and running bundle install,
I opened again the rails console and this time require 'rest-client' worked flawlessly
For me it was an issue with bundle (which I thought I had installed). Spoiler alert, I didn't, and this is how I fixed it. I'm on a Mac running OS X Yosemite and my terminal version is Darwin Kernel Version 14.3.0:
cd
gem install bundler
or
cd
sudo gem install bundler
If you get something along the lines of the following error:
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.
Finally, change your require line from:
require 'rest-client'
to
require 'rest_client'
Then run your code!
First ensure you have installed gem 'rest-client', ~> 1.8.0 on your gem file. Run bundle install and then require 'rest_client'. This worked for me.
Try require 'rest_client', instead of require 'rest-client'

Ruby gems in stand-alone ruby scripts

This is a really basic ruby gems question. I'm familiar with writing simple ruby scripts like this:
#!/usr/bin/ruby
require 'time'
t = Time.at(123)
puts t
Now I'd like to use my own ruby gem in my script. In my rails project I can simply require 'my_gem'. However this doesn't work in a stand-alone script. What's the best/proper way to use my own gem in a stand-alone ruby script?
You should be able to simply require it directly in recent versions of Ruby.
# optional, also allows you to specify version
gem 'chronic', '~>0.6'
# just require and use it
require 'chronic'
puts Chronic::VERSION # yields "0.6.7" for me
If you are still on Ruby 1.8 (which does not require RubyGems by default), you will have to explicitly put this line above your attempt to load the gem:
require 'rubygems'
Alternatively, you can invoke the Ruby interpreter with the flag -rubygems which will have the same effect.
See also:
http://docs.rubygems.org/read/chapter/3#page70
http://docs.rubygems.org/read/chapter/4
You could use something like this. It will install the gem if it's not already installed:
def load_gem(name, version=nil)
# needed if your ruby version is less than 1.9
require 'rubygems'
begin
gem name, version
rescue LoadError
version = "--version '#{version}'" unless version.nil?
system("gem install #{name} #{version}")
Gem.clear_paths
retry
end
require name
end
load_gem 'your_gem'
It is to be noted that bundler itself can deal with this. It's particularly interesting since bundler ships with Ruby by default since version 2.6, and you don't need to install it manually anymore.
The idea is:
to require bundler/inline at the top of your script,
to use the gemfile method, and declare the gems you need inside a block, like you'd do in a Gemfile,
after the end of this section, your gems are available!
For instance:
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'rainbow'
end
# From here on, rainbow is available so I can
# print colored text into my terminal
require 'rainbow'
puts Rainbow('This will be printed in red').red
The official documentation can be found on bundler website: bundler in a single file ruby script
Installing gems with something like the following should work. Be mindful of whether gems should be installed as part of system ruby or a user's.
#!/usr/bin/env ruby
require 'rubygems'
def install_gem(name, version=Gem::Requirement.default)
begin
gem name, version
rescue LoadError
print "ruby gem '#{name}' not found, " <<
"would you like to install it (y/N)? : "
answer = gets
if answer[0].downcase.include? "y"
Gem.install name, version
else
exit(1)
end
end
end
# any of the following will work...
install_gem 'activesupport'
install_gem 'activesupport', '= 4.2.5'
install_gem 'activesupport', '~> 4.2.5'
# require as normal (since not all gems install & require with same name) ...
require 'active_support/all'
...
I'm not sure if I understood your question right, but perhaps you don't have a gem, even if you write it (you are a beginner, so perhaps you misunderstood the concept of gems).
Just to be sure: You have a gemspec for your gem? If not, then you have no gem, but a single script.
When you want your own script inside another script, you may just do:
require 'my_script'
With ruby 1.8 this works fine, if my_script.rb is in the same folder as your main script. With ruby 1.9+ you can use:
require_relative 'my_script'
There is no need of a gem in this case.

Require a specific version of ActiveRecord

I have both Rails 2.3.4 and Rails 3.0.0.beta installed on my local machine. I am using ActiveRecord in a stand alone ruby script and when I do require 'active_record' 3.0.0.beta is loaded. How can I force it to require 2.3.4 instead? (without uninstalling 3.0.0.beta)
This is covered in the RubyGems manual # http://docs.rubygems.org/read/chapter/4
do:
require 'rubygems'
gem 'activerecord', '= 2.3.4'
A little trick is require 'activerecord' when you want 2.3.5 and 'active_record' when you want 3.0.0.beta.
You have a warning when you using activerecord require but it's load only 2.3.5.
After if you want manage several gem in same computer, you can try rvm and gemset system. It's really great.

How do I get an installed ruby gem included in Rails?

I am attempting to get a gem I installed working in a Rails application. I can require the gem just fine in a Ruby program that I run from the command line using:
require 'nokogiri'
But when I attempt to do the same in one of my Rails controllers it errors saying "no such file to load -- nokogiri".
I tried using the full path to the lib/nokogiri.rb file, but that fails because it cannot find "nokogiri/native".
Better, place the following in your environment.rb file:
Rails::Initializer.run do |config|
...
config.gem :nokogiri
...
end
This will tell Rails that you depend on that particular gem. It also allows you to specify particular versions, and it will automatically keep all your gems synched, or unpack them into vendor/gems if you so wish.
I had a similar error but simply forgot to put the following in my environment.rb file: (note the quoted "nokogiri")
Rails::Initializer.run do |config|
...
config.gem "nokogiri"
...
end
Ok I figured it out. This is going to sound pretty stupid...but oh well...
It turns out I had two installations of ruby on my machine. I use InstantRails to serve my test applications and it comes prepackaged with an installation of ruby. I had another installation however outside of this and it was here that nokogiri had been installed, not in the installation in InstantRails.
In any case they were looking in different spots for the gems.
Try the following
require 'rubygems'
gem 'nokogiri'
If you are on some form of *nix then did you get any errors when you installed the gem, particularly errors stating that the gem was not on the path. This may happen if you have installed the gem as yourself rather than as root and you do not have your personal gem library in your gem path.
If you always install your gems using
sudo gem install some_gem_name
then you should not get that problem.

Resources