It's possible, for example, to use ActiveRecord inline in a Ruby script. I like this a lot to report bugs, test features and share gists.
I'm wondering if the same could be done for a Rails webservice? (I'm mainly interested in getting the controller layer to work, the rest should be easy to add on demand.) Something along these lines:
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem 'rails', '~> 6.0.0'
end
require 'rails/commands'
APP_PATH = File.expand_path('config/application', __dir__)
Rails::Command.invoke('server')
When toying around with this it did seem that an external entry point (APP_PATH) is required. So alternatively, an acceptable approach would be to cram all config into the single entry point. I couldn't get this to work so far.
The Rails Initialization Process is the best resource I found about this so far.
I produced a minimal Rails app to get started as follows:
rails new min-rails --skip-keeps --skip-action-mailer --skip-action-mailbox --skip-action-text --skip-active-record --skip-active-storage --skip-puma --skip-action-cable --skip-sprockets --skip-spring --skip-listen --skip-javascript --skip-turbolinks --skip-test --skip-system-test --skip-bootsnap --api
cd min-rails
rm -rf app/jobs app/models config/initializers config/locales lib log public tmp vendor config/environments/test.rb config/environments/production.rb config/credentials.yml.enc config/master.key bin/rake bin/setup bin/bundle
I ended up with the following script:
inline-rails.rb
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem 'rails', '~> 6.0.0'
end
require "action_controller/railtie"
class App < Rails::Application
routes.append do
get "/hello/world" => "hello#world"
end
config.consider_all_requests_local = true # display errors
end
class HelloController < ActionController::API
def world
render json: {hello: :world}
end
end
App.initialize!
Rack::Server.new(app: App, Port: 3000).start
Run it as:
ruby inline-rails.rb
Related
I have an engine, that has gem dependency. This gem has rake task to install migrations:
rake acts_as_taggable_on_engine:install:migrations
What is the proper way to install migration? When I run this command from host app or my engine I getting
Don't know how to build task
Add the gem dependency to you gemspec:
Gem::Specification.new do |s|
# ...
s.add_dependency 'acts-as-taggable-on', '~> 6.0'
# ...
end
Then require the gem in your engine:
# lib/my_engine/engine.rb
require 'acts-as-taggable-on'
module MyEngine
class Engine < ::Rails::Engine
isolate_namespace Chatty
end
end
ActsAsTaggableOn should be loaded through the main file which requires the engine as well unlike some gems where you require gemname/engine - and the file naming is not snake_case like most gems.
Then run bundle install and rake acts_as_taggable_on_engine:install:migrations in the folder of the dummy application (or the host).
max#MaxBook ~/p/c/t/dummy> rake acts_as_taggable_on_engine:install:migrations
Copied migration 20181030123059_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb from acts_as_taggable_on_engine
Copied migration 20181030123060_add_missing_unique_indices.acts_as_taggable_on_engine.rb from acts_as_taggable_on_engine
Copied migration 20181030123061_add_taggings_counter_cache_to_tags.acts_as_taggable_on_engine.rb from acts_as_taggable_on_engine
Copied migration 20181030123062_add_missing_taggable_index.acts_as_taggable_on_engine.rb from acts_as_taggable_on_engine
Copied migration 20181030123063_change_collation_for_tag_names.acts_as_taggable_on_engine.rb from acts_as_taggable_on_engine
Copied migration 20181030123064_add_missing_indexes_on_taggings.acts_as_taggable_on_engine.rb from acts_as_taggable_on_engine
I don't know why but invoking the command through bundler (bundle exec ...) does not work. This may give problems with RVM if you are using shims.
You can also create a generator for your engine that invokes the task:
# lib/generators/my_engine/install/install_generator.rb
module MyEngine
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path('templates', __dir__)
desc "Installs MyEngine"
def copy_initializer
# template 'my_engine.rb', 'config/initializers/my_engine.rb'
rake "acts_as_taggable_on_engine:install:migrations"
end
end
end
Which you can then run with rails g my_engine:install.
I have a gem that I am making and it is located at the same level as a rails app.
I am trying to use the gem in the rails app, but am not able to make it work - the constant I am trying to use, which is defined in the gem, is not accessible to the rails app for some reason.
What am I doing wrong here? What steps can I take to begin debugging the cause of the problem?
In the rails console, $:.grep /mygem/ shows me ["/Users/zabba/mygem/lib"]
Directory structure, with the contents of certain files:
~/mygem/
lib/
mygem/
some_class.rb
module Mygem
class SomeClass
end
end
mygem.rb
require 'mygem/some_class'
~/railsapp/
Gemfile:
gem 'mygem', path: '../mygem', require: 'mygem'
app/
models/
a_model.rb:
# require 'mygem' cannot find file
class AModel
def hello_world
SomeClass.new # Cannot find constant
Mygem::SomeClass.new # Cannot find constant
end
end
Can you create a folder vendor/gems and copy your gem in there. Then in you Gemfile
Gemfile
gem 'mygem', :path => "vendor/gems/mygem-0.0.1"
Then bundle install
When I run test.rb (see below) as a separate ruby file from within my rails project it works fine but when I wrap it as a module to be called from a controller it gives me:
LoadError (no such file to load -- eventmachine):1 in 'ModuleTest'
The gem is installed (sudo gem install event machine and bundle install) and added to the gem file (gem 'eventmachine').
Could someone please advice on what it is that I'm missing?
Separate file (called through: $ ruby lib/test.rb):
require 'rubygems'
require 'eventmachine'
require 'em-http'
require 'fiber'
def doStuff
end
doStuff
Module:
require 'eventmachine'
require 'em-http'
require 'fiber'
module ModuleTest
def doStuff
end
end
Controller:
require 'moduletest'
class MyController < ApplicationController
doStuff
end
Add
gem 'eventmachine'
Into your Gemfile. Then execute bundle install.
If you want to use a new gem in your rails project, you need to add it into Gemfile. To learn more, visit http://gembundler.com/
gem install rubyoverflow
irb
> require 'rubyoverflow'
=> true
But:
require 'rubyoverflow'
include Rubyoverflow
class QuestionsController < ApplicationController
def question_by_tag
ruby_q = Questions.retrieve_by_tag('ruby')
Get error:
LoadError in
QuestionsController#question_by_tag no
such file to load -- rubyoverflow
Rails.root:
D:/artefacts/dev/projects/stack
app/controllers/questions_controller.rb:1:in
`'
This error occurred while loading the
following files: rubyoverflow
Is there any special rules to import moduled in the controller?
why do you use both require and include? include Rubyoverflow will be enough
UPD
For gem you should add it into your Gemfile (Rails 3.x) or config/environment.rb (Rails 2.x)
# Gemfile
gem "rubyoverflow"
# environment.rb
config.gem "rubyoverflow"
Then run bundle for Rails 3.x and rake gems:install for Rails 2.x
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.